简体   繁体   English

如何查找集合的子文档并使用 Mongoose/MongoDB 更新它?

[英]How to find a subdocument of a collection and update it with Mongoose/MongoDB?

I have a basic document like so:我有一个像这样的基本文件:

_id: fm393nrr,
name: 'My Event'
members: [{
   user: 94iru134nf
   attending: 1
}, {
   user: er9fr94,
   attending: 0
}]

How would I change a members attending based on their user ?我将如何根据他们的user更改attending的成员?

For example, something like:例如,类似于:

var eventToFind = 'fm393nrr'; //usually retrieved by req.params
var userToFind = 'er9fr94'; //usually retrieved by req.body.user

Event.findOneAndUpdate({
       _id: eventToFind
    }, {
       $set: {members.attending: {.....}}
    }
).exec(function(){....});

In the above, I am trying to set the member of er9fr94 to have attending of 1. Code is very off, but was a long shot attempt.在上文中,我想设置的成员er9fr94attending 1.代码是非常关闭,但一个长镜头的尝试。 Never worked with subdocuments/embedded documents before.以前从未使用过子文档/嵌入文档。

Add double quotes when dealing with nested objects.处理嵌套对象时添加双引号。 The $ becomes equal to the array index of the match. $变得等于匹配的数组索引。

Try this:尝试这个:

Event.findOneAndUpdate({
   _id: eventToFind,
   "members.user":userToFind,
}, {
   $set: {"members.$.attending": {.....}}
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM