Reputation: 47911
Using addToSet
with mongoose, how do I get back the newly inserted id of the object. In this example the _id
of the friend added to the friends collection. Friend is defined in the model as having an _id
field.
db.user.update(
{ _id: 1 },
{ $addToSet: { friends: {name:"bob"} } }
)
Upvotes: 2
Views: 415
Reputation: 2669
addToSet() will adds an object to an array. So if I understand your question correctly, this might work:
db.user.update(
{ _id: 1 },
{ $addToSet: { friends: {name:"bob"} } },
{ new: true}
).exec( (err, user) => {
user.friends // an array
var bob = user.friends.filter( x => x.name == "bob");
bob._id
})
Upvotes: 1