Fizzix
Fizzix

Reputation: 24375

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?

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. Never worked with subdocuments/embedded documents before.

Upvotes: 1

Views: 54

Answers (1)

RainingChain
RainingChain

Reputation: 7746

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": {.....}}
})

Upvotes: 1

Related Questions