Meteor中更新嵌套数组的Mongo操作

4

示例文档:

{
"_id" : "5fTTdZhhLkFXpKvPY",
"name" : "example",
"usersActivities" : [ 
    {
        "userId" : "kHaM8hL3E3As7zkc5",
        "startDate" : ISODate("2015-06-01T00:00: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
         }
    }
);

我很高兴能为您提供帮助。

2个回答

9
所以首先要说的是,对于你的情况而言,$elemMatch 是不必要的,因为你只想匹配单个数组属性。当你需要从同一数组元素中“两个或多个”属性来满足条件时,使用该运算符。否则,你只需要使用 "点表示法" 作为标准。
第二种情况涉及到 $push,该特定运算符表示“添加”元素到数组中。在你的情况下,你只想“更新”,因此正确的运算符为 $set:
Activity.update(
    { "_id": activityId, "usersActivities.userId": Meteor.userId() },
    {
        "$set": {
            'usersActivities.$.startDate': start,
            'usersActivities.$.endDate': end
        }
    }
)

所以这里的定位符号$是匹配数组元素中的“找到的索引”,并允许$set操作符“更改”在该“位置”匹配的元素。

如果Meteor.userId()不存在,如何插入带有“userID”,“startDate”和“endDate”的整个对象? - justdiehard

0
如果Meteor.userId()不存在,如何插入带有userIDstartDateendDate的整个对象? - justdiehard 6月14日20:20
如果您尝试进行新的插入操作,应该查看Meteor账户包,其中有像...的方法
Accounts.createUser(YOU_USER_SCHEME)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接