[英]How can I find pushed subdocument ids in mongoose during update?
我正在嘗試使用doc.updateOne
查找我插入到文檔中數組中的子文檔的_id
。 如何找到新推送的子文檔的_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?)
我在這里找到了答案
在更新我的文檔並將該ObjectId
分配給新插入的子文檔_id
之前,我只需要創建ObjectId
。 這是解決問題的簡單代碼:
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.