Home > Mobile >  How can I find pushed subdocument ids in mongoose during update?
How can I find pushed subdocument ids in mongoose during update?

Time:01-18

I am trying to find _id of subdocuments that I insert into an array inside my document using doc.updateOne. How can I find _id of newly pushed subdocuments?

This is what I've tried. But I'm afraid that when too many updates happen, I get a wrong _id

await model.updateOne({
    _id: docId
}, {
    $push: {
        arr: {a: 3, b: 4}
    }
});

const freshData = await model.findById(docId);
const id = freshData.arr[freshData.arr.length - 1];

console.log(id); // _id will be printed (But what if another $push happen before findById?)

CodePudding user response:

I've found an answer here

I only had to create ObjectId before updating my document and assigning that ObjectId to newly inserted subdocument _id. Here is a simple code that solves the problem:


const _id = new ObjectId();

await model.updateOne(
    { _id: docId },
    {
        $push: {
            arr: {_id, a: 3, b: 4}
        }
    });

console.log(_id); // _id will be printed
  • Related