Meteor mongo更新嵌套数组 [英] Meteor mongo updating nested array

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

问题描述

示例文档:

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

我是新的在mongoDB和我阅读关于更新嵌套数组的其他问题,我不能正确。我想做的是为给定userId的用户更改startDate和endDate。我的问题是,它总是将新对象推送到数组,而不是用给定的userId更改对象。

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

我将非常高兴的帮助。

解决方案

因此,第一个要说的是 $ elemMatch 不是必须的,因为您只想匹配单个数组属性。当您需要来自同一数组元素的两个或多个属性以匹配您的条件时,可以使用该运算符。否则,您只需使用点符号作为标准。 p>

第二种情况是 $ push ,其中该特定操作符意味着将元素添加到数组。在你的情况下,你只是想更新,因此这里的正确运算符是 $ set

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



因此, positions $ 运算符这里是与数组元素的found index匹配,允许 $ set 运算符来更改在该位置匹配的元素。


Example document:

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

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.

解决方案

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".

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

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