我有一個遞回嵌套的子檔案(陣列),一般看起來像:
parent:{
children:[{
field,
children:[{
field,
children:[{
...
}]
},
{
field,
children:[{
...
}]
},
...]
}
}
這意味著每個children子檔案可能有另一個嵌套的children子檔案。
我正在嘗試編輯一個子檔案(我們稱之為“子檔案”)。例如,我想在 3 級編輯子級。這意味著我需要向下 3 級子級,訪問子級并保存檔案(父級)。
我現在正在做的是將關卡發送給函式,以及我想添加給孩子的資訊。我找到了檔案(findOne到父母的 Id),往下走,嘗試編輯孩子,最后保存檔案:
await parentModel.findOne({'_id': parentId}).populate(/*population needed for the information*/)
.exec().then(async (result)=>{
let children = result.children;
for (let i=0; i<level;i ){
children = children.children;
}
children.push(child); //in my specific case I simply push the child to the children one level above
await result.save((e,doc)=>{...})
發生的事情是我確實看到它children.push(child)成功了,但是檔案沒有保存它(盡管該save功能也成功了)。
我認為這與我在children當地 ( let children...)接受的事實有關,但我不確定這是否屬實,所以我正在尋求建議。
uj5u.com熱心網友回復:
當您更改嵌套陣列時,您必須“告訴”已更改的貓鼬,因為默認情況下它無法識別它。
您可以使用 markModified('fieldName') 來做到這一點。
例子:
parent ---> a mongooose doc
parent.child.push({new child object});
parent.markModified('child);
parent.save();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/368872.html
標籤:javascript 节点.js MongoDB 猫鼬
上一篇:匹配條件一段時間后洗掉檔案?
