MonkeyBonkey
MonkeyBonkey

Reputation: 47911

How to get _id of inserted object in mongodb mongoose with addToSet

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

Answers (1)

vdj4y
vdj4y

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

Related Questions