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

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

问题描述

示例文档:

<代码>{"_id": "5fTTdZhhLkFXpKvPY",名称":示例",用户活动":[{"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,用户活动:{$elemMatch:{用户 ID:Meteor.userId()}}},{$推:{'usersActivities.$.startDate':开始,'usersActivity.$.endDate': 结束}});

如果能帮到你我会很高兴的.

解决方案

所以这里首先要说的是$elemMatch 在您的情况下不是必需的,因为您只想匹配单个数组属性.当您需要来自同一数组元素的两个或更多"属性来匹配您的条件时,您可以使用该运算符.否则,您只需使用 "dot notation" 作为标准.>

这里的第二种情况是 $push,其中该特定运算符的意思是将元素添加"到数组中.在您的情况下,您只想更新",因此此处正确的运算符是 $set:

Activity.update({_id":activityId,usersActivities.userId":Meteor.userId() },{$set":{'usersActivities.$.startDate':开始,'usersActivity.$.endDate': 结束}})

所以 位置 $ 运算符 这里是匹配来自数组元素的找到的索引"并允许 $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天全站免登陆