Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Mongoose: Get doc _id after upsert

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 (!topic/mongoose-orm/ehZ11QY-OUw), but Mongoose doesn't provides access to it (!topic/mongoose-orm/pSv6WrasvWg)


Problem courtesy of: AkerbeltZ


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 */
Solution courtesy of: Tom Ashworth


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Mongoose: Get doc _id after upsert


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription