简体   繁体   English

更新期间如何在 mongoose 中找到推送的子文档 ID?

[英]How can I find pushed subdocument ids in mongoose during update?

I am trying to find _id of subdocuments that I insert into an array inside my document using doc.updateOne .我正在尝试使用doc.updateOne查找我插入到文档中数组中的子文档的_id How can I find _id of newly pushed subdocuments?如何找到新推送的子文档的_id

This is what I've tried.这是我试过的。 But I'm afraid that when too many updates happen, I get a wrong _id但是我担心当发生太多更新时,我得到一个错误的_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?)

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 .在更新我的文档并将该ObjectId分配给新插入的子文档_id之前,我只需要创建ObjectId 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM