Meteor mongo 更新嵌套数组
Meteor mongo updating nested array
示例文档:
{
"_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
}
}
);
我很乐意提供帮助。
所以这里首先要说的是$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"作为标准。
第二种情况是 $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
}
}
)
所以这里的 positional $
operator 匹配数组元素中的 "found index" 并允许 $set
运算符 "change" 在 [=27= 处匹配的元素].
"What if Meteor.userId()
does not exist, how to insert the whole of object with userID
, startDate
and endDate
? – justdiehard Jun 14 at 20:20"
如果你尝试添加新的,你应该看看 Meteor Accounts 包,有像
这样的方法
Accounts.createUser(YOU_USER_SCHEME)
示例文档:
{
"_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
}
}
);
我很乐意提供帮助。
所以这里首先要说的是$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"作为标准。
第二种情况是 $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
}
}
)
所以这里的 positional $
operator 匹配数组元素中的 "found index" 并允许 $set
运算符 "change" 在 [=27= 处匹配的元素].
"What if Meteor.userId()
does not exist, how to insert the whole of object with userID
, startDate
and endDate
? – justdiehard Jun 14 at 20:20"
如果你尝试添加新的,你应该看看 Meteor Accounts 包,有像
这样的方法Accounts.createUser(YOU_USER_SCHEME)