gpt4 book ai didi

javascript - 如何对 mongodb 文档进行原子自定义更新?

转载 作者:行者123 更新时间:2023-12-03 02:54:24 24 4
gpt4 key购买 nike

我知道 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);
}

系统将调用此函数,该系统不会等待已解决的 promise 继续工作:可以有多个同步调用。

有没有办法重写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);

关于javascript - 如何对 mongodb 文档进行原子自定义更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47701005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com