流星蒙戈更新嵌套数组 [英] Meteor mongo updating nested array

查看:141
本文介绍了流星蒙戈更新嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如文档:

{
"_id" : "5fTTdZhhLkFXpKvPY",
"name" : "example",
"usersActivities" : [ 
    {
        "userId" : "kHaM8hL3E3As7zkc5",
        "startDate" : ISODate("2015-06-01T00:00:00.000Z"),
        "endDate" : ISODate("2015-06-01T00:00:00.000Z")
    }
]
}

我在MongoDB中新和我读到有关更新嵌套数组的其他问题,我不能做正确。我想要做的是改变的startDate和结束日期与给定的用户id用户。我的问题是,它总是推新对象阵列,而​​不是与给定用户id改变对象。

I'm new in mongoDB and I read other questions about updating nested array and I can't do it properly. What I want to do is to change startDate and endDate for user with given userId. My problem is that it always pushes new object to array instead of changing object with given userId.

Activity.update( 
    _id: activityId, usersActivities: {
         $elemMatch: {
             userId: Meteor.userId()
         }
     }},
    {
        $push: {
            'usersActivities.$.startDate': start,
            'usersActivities.$.endDate': end
         }
    }
);

我会很高兴帮助。

I will be really glad of help.

推荐答案

所以在这里说的第一件事就是 $ elemMatch 没有你的情况需要,你只需要匹配一个数组属性。您可以使用该操作符时,你需要从同一个数组元素两个或更多的属性,以符合您的条件。否则,你只需要使用点号作为标准。

So the first thing to say here is the $elemMatch is not required in your case as you only want to match on a single array property. You use that operator when you need "two or more" properties from the same array element to match your conditions. Otherwise you just use "dot notation" as a standard.

下面第二个案例是 $推 ,在那个特定的运营商意味着元素添加到数组。你的情况,你只是想升级,所以正确的操作这里是 <强> $设置

The second case here is with $push, where that particular operator means to "add" elements to the array. In your case you just want to "update" so the correct operator here is $set:

Activity.update(
    { "_id": activityId, "usersActivities.userId": Meteor.userId() },
    {
        "$set": {
            'usersActivities.$.startDate': start,
            'usersActivities.$.endDate': end
        }
    }
)

于是位置 $ 运营商的这里是从数组元素中的发现指数相匹配,并且允许 $设置运营商变的元素在那个位置相匹配

So the positional $ operator here is what matches the "found index" from the array element and allows the $set operator to "change" the elements matched at that "position".

这篇关于流星蒙戈更新嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆