Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: Get doc _id after upsert

is there any way to get the record _id after an upsert?

I've seen this post (How to insert a doc into mongodb using mongoose and get the generated id?), but this is oriented only to inserts, not updates.

Also, using the MongoDB you can use get the _id using getlasterror (https://groups.google.com/forum/?fromgroups=#!topic/mongoose-orm/ehZ11QY-OUw), but Mongoose doesn't provides access to it (https://groups.google.com/forum/?fromgroups=#!topic/mongoose-orm/pSv6WrasvWg)

Thanks

like image 303
AkerbeltZ Avatar asked Dec 21 '22 14:12

AkerbeltZ


1 Answers

Use Mongoose's findOneAndUpdate method with upsert: true in the options object.

var query = { name: 'borne' },
    data = { name: 'jason borne' },
    options = { upsert: true };
Model.findOneAndUpdate(query, data, options, function (err, object) {
    /* use object._id */
});
like image 89
Tom Ashworth Avatar answered Dec 24 '22 00:12

Tom Ashworth