Javascript 查找,如果不存在,则插入,vulenrability

Javascript 查找,如果不存在,则插入,vulenrability,javascript,node.js,mongodb,mongoose,fastify,Javascript,Node.js,Mongodb,Mongoose,Fastify,至少在同一时间执行10次以上的请求,此代码将插入4条相同的记录,但必须只插入1条 用户只能启动1个活动游戏。(在活动游戏字段中finished=false) 同时记录10个请求: performing request inserted performing request performing request inserted performing request inserted inserted performing request errored performing request er

至少在同一时间执行10次以上的请求,此代码将插入4条相同的记录,但必须只插入1条

用户只能启动1个活动游戏。(在活动游戏字段中
finished=false

同时记录10个请求:

performing request
inserted
performing request
performing request
inserted
performing request
inserted
inserted
performing request
errored
performing request
errored
performing request
errored
performing request
errored
performing request
performing request
errored
errored

事务对我没有帮助。

当然,这段代码容易出现争用情况。为了避免这种情况,您只需使用一个。将其应用于文档的
uid
字段,其中
finished:false
et瞧,您现在不能为同一用户插入两个活动的游戏。

您的uid不同,因此它将插入这些时间。如果您将传递相同的uid,那么它将根据您的要求工作

你可以试试这些。和读取save()功能

console.log('performing request');
const activeGame = await db.Game.findOne({ _id: uid, finished: false });
if (activeGame == null) {
      console.log('inserted');
    const game = new db.Game({
        moves: new Array(5*5).fill(0)
    });
    game.save();
    return game;
} else {
    console.log('errored');
    return { error: 'Finish previous game.' };
}


如何在插入中使用它?@koljacheesch:文档中有一些例子。查找
upsert
option我已经读过这篇文章了,但是我不知道如何使用这个函数插入。在这个问题中,我还编写了一小部分代码,activeGame find发生在其他地方(在中间件中),但插入发生在game.js中。我也不知道如何分割这个函数。如果做同样的代码,它会破坏项目结构…@koljacheesch:如果我今天晚些时候有时间,我会尝试做一个例子。至于你的另一个问题(发现和更新发生在不同的地方):Maaaybe你可以通过创造性地应用独特的索引来解决它。但更可能的是,你必须重新考虑这个设计。谢谢。嗯,我需要一点其他的逻辑,我根本不需要更新,我需要findOneAndInsert,而不是findOneAndUpdate…你是如何推断uid会有所不同的?还有,为什么你认为它不仅仅是一个常规字段?我的uid是一样的。我正在传递相同的uid变量。如果它不是一个常规字段,那么为什么要在save()中更新它?不,uid不能是唯一的\u id。用户可能有很多已完成的游戏。但活跃的游戏只有一个。
console.log('performing request');
const activeGame = await db.Game.findOne({ _id: uid, finished: false });
if (activeGame == null) {
      console.log('inserted');
    const game = new db.Game({
        moves: new Array(5*5).fill(0)
    });
    game.save();
    return game;
} else {
    console.log('errored');
    return { error: 'Finish previous game.' };
}
console.log('performing request');
const activeGame = await db.Game.findOne({ _id: uid, finished: false });
activeGame.save()