I have tried to implement this in several ways and none seem to work. All I need to do is change the Status
value of a specific Notifications
object (found by its _id
) from 0
to 1
.
我试图以几种方式实现这一点,但似乎都没有。我需要做的就是将特定Notifications对象的Status值(由其_id找到)从0更改为1。
Example JSON:
{
"_id": "577fbf0c7c6e88600ede5e73",
"updatedAt": "2016-07-14T11:27:18.670Z",
"createdAt": "2016-07-08T14:56:12.013Z",
"Name": "Name",
"Email": "test@test.com",
"Notifications": [
{
"_id": "5787644108edec801e9cd0ab",
"Title": "They commented on This",
"Type": 1,
"Status": 0,
"TeamID": "578357109bb105602b1cba27",
"DraftID": "578357b89bb105602b1cba2a"
},
{
"_id": "578777167d1f3424251c361f",
"Title": "He commented on That",
"Type": 1,
"Status": 0,
"TeamID": "578357109bb105602b1cba27",
"DraftID": "578357b89bb105602b1cba2a"
}
]
.....
}
My route:
router.post('/notification', function (req, res) {
UserProfile.update({
'Notifications._id' : req.body.NotificationID
}, {
'$set' : {
'Notifications.$.Status' : 1
}
}, function (err) {
if (err)
res.send(err);
})
});
I don't get any errors and the update doesn't seem to happen. What could the problem be?
我没有收到任何错误,似乎没有更新。问题是什么?
3 个解决方案
#1
2
Is the type of Notifications._id
ObjectId? If so, try cast req.body.NotificationId
to ObjectId. Change the query to
Notifications._id是ObjectId的类型吗?如果是这样,请尝试将req.body.NotificationId强制转换为ObjectId。将查询更改为
{'Notifications._id' : mongoose.Types.ObjectId(req.body.NotificationID)}
#2
0
Try '$set' instead of $set. Ensure that you are getting id coming in correctly. Update callback comes with updated document - print that to know what happens.
尝试'$ set'而不是$ set。确保您正确识别ID。更新回调附带更新的文档 - 打印以了解发生的情况。
#3
0
The $
is referring only the first item in the array. If you want to update all you have to use find and save:
$仅指代数组中的第一项。如果您想要更新所有必须使用查找和保存:
UserProfile.findOne({
'Notifications._id' : req.body.NotificationID
}, function(err, doc) {
_.find(doc.Notifications, {_id: req.body.NotificationID}).Status = 1;
doc.save(function (err) {
if (err)
res.send(err);
})
})
#1
2
Is the type of Notifications._id
ObjectId? If so, try cast req.body.NotificationId
to ObjectId. Change the query to
Notifications._id是ObjectId的类型吗?如果是这样,请尝试将req.body.NotificationId强制转换为ObjectId。将查询更改为
{'Notifications._id' : mongoose.Types.ObjectId(req.body.NotificationID)}
#2
0
Try '$set' instead of $set. Ensure that you are getting id coming in correctly. Update callback comes with updated document - print that to know what happens.
尝试'$ set'而不是$ set。确保您正确识别ID。更新回调附带更新的文档 - 打印以了解发生的情况。
#3
0
The $
is referring only the first item in the array. If you want to update all you have to use find and save:
$仅指代数组中的第一项。如果您想要更新所有必须使用查找和保存:
UserProfile.findOne({
'Notifications._id' : req.body.NotificationID
}, function(err, doc) {
_.find(doc.Notifications, {_id: req.body.NotificationID}).Status = 1;
doc.save(function (err) {
if (err)
res.send(err);
})
})