为什么我的Mongoose查询不更新MongoDB数据库中的嵌套数组中的值?
我试图用几种方式来实现这一点,而且似乎没有任何工作。 我需要做的只是将特定Notifications
对象(由其_id
find)的Status
值从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); }) });
我没有得到任何错误,更新似乎没有发生。 问题是什么?
是Notifications._id
ObjectId的types? 如果是这样,请尝试将req.body.NotificationId
为ObjectId。 将查询更改为
{'Notifications._id' : mongoose.Types.ObjectId(req.body.NotificationID)}
尝试'$ set'而不是$ set。 确保你得到正确的身份证。 更新callback来与更新的文件 – 打印,知道会发生什么。
$
是只引用数组中的第一个项目。 如果你想更新所有你必须使用查找和保存:
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); }) })
- 如何从nodejs实时发送stdout到angularjs?
- grunt.jsconfiguration中常见configuration选项的inheritance
- 如何检查一个string是否与星号匹配
- 骨干模型不是呈现默认? 需要玉和骨干大师
- configuration依赖于RequireJS时,使用RequireJSconfiguration模块
- 节点js POST mysite / uploads 404(未find)上传到天青,但本地工作
- 如何用bower构build依赖项(ex highlight.js)?
- 如何通过HTTPS将Firebase令牌发送到后端(Node / Express)
- Bootstrap和JQuery与节点js