[英]How to do an atomic custom update of a mongodb document?
I am aware that MongoDB can do atomic updates using findOneAndModify
but this only permits basic operations like set or increment. 我知道MongoDB可以使用
findOneAndModify
进行原子更新,但这仅允许进行基本操作(例如设置或递增)。
What I need is to apply a custom function to transform my document: 我需要应用自定义函数来转换文档:
const updateDoc = async (event) => {
const oldState = await db.collection(collectionName).findOne({ name });
const newState = customFunction(oldState, event);
await db.collection(collectionName).replaceOne({ name }, newState);
}
This function will be called by a system that won't wait for a resolved promise to continue working: there can be multiple synchronous calls. 该函数将由不等待已解决的诺言继续工作的系统调用:可以有多个同步调用。
Is there a way to rewrite updateDoc
to make it atomic, so that when we do: 有没有一种方法可以重写
updateDoc
使其原子化,以便在执行此操作时:
updateDoc(event1); // note the absence of await
updateDoc(event2);
We can be sure that the stored doc will be customFunction(customFunction(initState, event1), event2)
? 我们可以确定存储的文档将是
customFunction(customFunction(initState, event1), event2)
吗?
Thanks 谢谢
A possible solution would be a task queue, that shedules one update after another: 可能的解决方案是任务队列,该任务队列一次又一次地进行更新:
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;
}
}
Usable like this: 可以这样使用:
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.