I have a function that is supposed to find a question by "ID" from the mongo database and return it, if it doesn't find one it creates one and then returns it. it is the only function in my code that is able to create new question entities in the database. here it is: (btw i am using the official MongoDb driver for nodeJs)
function getQuestionEntity(questionID, cb){
const questions = db.collection('questions')
questions.findOneAndUpdate(
{ID: questionID},
{$setOnInsert:
{
ID: questionID,
rating: 1.5,
options: 4,
answeredRight: 0,
answeredWrong: 0
}
},
{
returnOriginal: false,
upsert: true
},
(err, r)=>{
if(err){throw new Error(err)}
cb(r.value)
}
)
}
I have read that findOneAndUpdate is an atomic operation, which means that even if i loop this function asynchronously to the end of times, still i will not get two question entities with the same "ID" field in the database, yet that is exactly what happens.
Is there anything wrong with my code? am i wrong about my assumptions?
via Maayan Blum
No comments:
Post a Comment