現在我更新多個子文檔與更新具有不同ID的多個文檔MongoDB中
var positions = [
{ id: '1', position: { x: 0, y: 0 } },
...
];
positions.forEach(element => {
Model.findOneAndUpdate({ _id: modelId, 'elements._id': element.id }, {
$set: {
'elements.$.position': element.position
}
});
});
但有可能調用數據庫中只有1個電話嗎?
編輯
我可以,例如,做
Model.findById(modelId).then(model => {
positions.forEach(element => {
const doc = model.elements.id(element.id);
doc.position = element.position;
});
model.save();
});
但它有更好的表現?
編輯2
我試着實現你的建議,但沒有任何反應。
我已經調試了一下,似乎沒有什麼是代碼的第一行後發生的事情:
console.log('this is printed')
const batch = ModelName.initializeUnorderedBulkOp();
console.log('this is _not_ printed')
你知道是什麼原因?我沒有收到任何錯誤消息。
編輯3
var batch = ModelName.initializeUnorderedBulkOp();
positions.forEach(element => {
batch.findOneAndUpdate({ _id: modelId, 'elements._id': element.id }, {
$set: {
'elements.$.position': element.position
}
});
});
batch.execute().then(() => {
console.log('success');
}).catch(err => {
console.log(err);
});
你無法批量恆定的。它需要是可變的,因爲我們正在將操作添加到批處理過程。把它變成一個變量。 – Rafael
它不適用於'var batch = ModelName.initializeUnorderedBulkOp();'。 – Jamgreen
請發佈您的代碼。你是否像我的例子一樣加入批處理操作?你是否以我的例子調用'execute()'? – Rafael