[英]How to do an atomic custom update of a mongodb document?
我知道MongoDB可以使用findOneAndModify
进行原子更新,但这仅允许进行基本操作(例如设置或递增)。
我需要应用自定义函数来转换文档:
const updateDoc = async (event) => {
const oldState = await db.collection(collectionName).findOne({ name });
const newState = customFunction(oldState, event);
await db.collection(collectionName).replaceOne({ name }, newState);
}
该函数将由不等待已解决的诺言继续工作的系统调用:可以有多个同步调用。
有没有一种方法可以重写updateDoc
使其原子化,以便在执行此操作时:
updateDoc(event1); // note the absence of await
updateDoc(event2);
我们可以确定存储的文档将是customFunction(customFunction(initState, event1), event2)
吗?
谢谢
可能的解决方案是任务队列,该任务队列一次又一次地进行更新:
class Scheduler {
constructor(){
this.running = false;
this.queue = [];
}
add(el){
this.queue.push(el);
if(!this.running) this.run();
}
async run(){
this.running = true;
while(this.queue.length) await this.queue.shift();
this.running = false;
}
}
可以这样使用:
const dbTasks = new Sheduler();
const updateDoc = async (event) => dbTasks.add( _ => {
const oldState = await db.collection(collectionName).findOne({ name });
const newState = customFunction(oldState, event);
await db.collection(collectionName).replaceOne({ name }, newState);
});
updateDoc(evt1);
updateDoc(evt2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.