Javascript 为什么我的Mongoose查询不更新MongoDB数据库中嵌套数组中的值?
我尝试了几种方法来实现这一点,但似乎都没有效果。 我所需要做的就是将特定的Javascript 为什么我的Mongoose查询不更新MongoDB数据库中嵌套数组中的值?,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我尝试了几种方法来实现这一点,但似乎都没有效果。 我所需要做的就是将特定的通知对象(通过其\u id找到)的状态值从0更改为1 JSON示例: { "_id": "577fbf0c7c6e88600ede5e73", "updatedAt": "2016-07-14T11:27:18.670Z", "createdAt": "2016-07-08T14:56:12.013Z", "Name": "Name", "Email": "test@test.com
通知
对象(通过其\u id找到)的状态
值从0
更改为1
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"
}
]
.....
}
我的路线:
router.post('/notification', function (req, res) {
UserProfile.update({
'Notifications._id' : req.body.NotificationID
}, {
'$set' : {
'Notifications.$.Status' : 1
}
}, function (err) {
if (err)
res.send(err);
})
});
我没有收到任何错误,更新似乎也没有发生。
可能是什么问题?尝试使用“$set”而不是$set。
确保您的id正确输入。
更新回调附带更新的文档-打印该文档以了解发生了什么。该$
仅引用数组中的第一项。如果要更新所有必须使用的内容,请使用“查找并保存”:
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);
})
})
是通知的类型。\u id
ObjectId?如果是这样,请尝试将req.body.NotificationId
转换为ObjectId。将查询更改为
{'Notifications._id' : mongoose.Types.ObjectId(req.body.NotificationID)}
它只意味着更新一个由其_id属性引用的特定通知对象。好的,但它不会工作,因为您要处理整个文档。我会修正我的答案谢谢你的回答。它抛出了此错误:ReferenceError:\未定义
它是lodash。如果你没有,就用过滤器你是说这个吗<代码>{ok:1,nModified:0,n:0}
在设置后添加{'$new':true}作为参数-检查更新的文档是的,这有效!非常感谢你。你是否有一个参考链接来解释这一点?我是新手,所以我想检查一下out@Poot87好!!在mongodb和mongoose中,ObjectId
type与String
type不同。你可以在网站上查看猫鼬的种类。