AkerbeltZ
AkerbeltZ

Reputation: 589

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

Upvotes: 4

Views: 6648

Answers (4)

Vishal Pathriya
Vishal Pathriya

Reputation: 67

const updateUser = await userModel.findByIdAndUpdate(
    { _id: uid },
    {
        name: name
        time: createdAt,
    }
).session(session);

let shallowCopy = {...updateUser}._doc;
console.log("shallowCopy", shallowCopy);

sometime we ned to delete some parameter like id. > ._doc will get updated/inserted data you may delete id using js delete operator

delete shallowCopy.id;

Upvotes: 0

Anonymous Creator
Anonymous Creator

Reputation: 3819

If you want the updated document returned, and in cases where it didn't exist and was upserted the new document. Below is the option you need to set.

set new: true to the options: options = { upsert: true, new: true };

Source: Based on Jamiel's comment, I am adding his comment as an answer as it was hard time finding for me to get that _id when no document existed and created by upsert (And I was trying to create my own extended method).

Upvotes: 1

solo
solo

Reputation: 783

Another possibility with promises:

Model.findOneAndUpdate(query, data, options, function (err, object) {
})).then((result) => {
    /* return result.upserted[0]._id */
})

...where result is the following:

{ n: 1,
  nModified: 0,
  upserted: [ { index: 0, _id: /* some id */ } ],
  ok: 1 }

Upvotes: 0

Tom Ashworth
Tom Ashworth

Reputation: 2665

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 */
});

Upvotes: 11

Related Questions