mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

can't update document before next request

Open guftall opened this issue 9 years ago • 2 comments

hi.

i'm using some code like this:

user.findFlag in initial is 1


db.User.find({ _id: 1}, (err, user) => {
if(user.findFlag === 1){

// do some other things

db.User.findOneAndUpdate(
            { _id: 1 },
            { findFlag: 0}, { upsert: true }, (err, user) => {
                if (err) return callback(err)
                
                callback(null, user)
            });
}
else if(user.findFlag === 0){
db.User.findOneAndUpdate(
            { _id: 1 },
            { findFlag: 1}, { upsert: true }, (err, user) => {
                if (err) return callback(err)
                
                callback(null, user)
            });
}
})

if client request more than one time without delay, user.findFlag doesnt change and just if(user.findFlag === 1) excuted. i know it is because of async but how to fix it?

nodejs: 8.3.0, express 4.15.4, mongoose 4.11.9

guftall avatar Sep 03 '17 12:09 guftall

Hi, As I understood, you want to prevent further updates while the previous one is not finished. As I know, MongoDB makes write lock to guarantee that only one write operation can be performed at a time at the same document, so there will not be any problems, next updates won't change anything. If there is conflict, MongoDB will transparently retry the operation. To prevent such things you can disable updates without delay on the client side (for example simply disabling the button).

koliaVasyliv avatar Sep 03 '17 21:09 koliaVasyliv

Yeah this is a tricky one because you're using upsert as well. We'll write a locking plugin to help with this but a quick solution would be to use mongoose versioning and increment __v when updating:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const GITHUB_ISSUE = `gh-5614`;
var uri = `mongodb://localhost:27017/${GITHUB_ISSUE}`;

exec();

async function exec() {
  try {
    mongoose.connect(uri, { useMongoClient: true });

    var TestSchema = new Schema({ name: String });

    var TestModel = mongoose.model('Test', TestSchema);

    let doc = await TestModel.create({ name: 'test' });
    doc = await TestModel.findById(doc._id);

    const res = await Promise.all([
      TestModel.findOneAndUpdate({ _id: doc._id, __v: doc.__v }, {
        $set: { name: doc.name + '!' },
        $inc: { __v: 1 }
      }),
      TestModel.findOneAndUpdate({ _id: doc._id, __v: doc.__v }, {
        $set: { name: doc.name + '!' },
        $inc: { __v: 1 }
      })
    ]);

    console.log(res);
  } catch (error) {
    console.error(`Error: ${error}\n${error.stack}`);
    process.exit(2);
  }
}

vkarpov15 avatar Sep 07 '17 23:09 vkarpov15