Im trying to insert new competitor if not exist, else only updating it, but im getting the following error:
(node:4628) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: Updating the path 'competitors' would create a conflict at 'competitors'
This is my model regarding competitors:
competitors : [
{
userid: {type: String, default: 'x'},
amount: {type: Number, default: 0},
reward: {type: Number, default: 0},
}
],
here is the piece of code that is running, but fails and reproduce the code
var newInsertMent = {userid: user._id, amount: 0};
return Competition_global.findOneAndUpdate(
{"competitors.userid": user._id, _id: globalCompetition._id},
{ $addToSet: {"competitors": newInsertMent}, $inc: {"competitors.$.amount": amount}},
{upsert: true,new: true}
).then(function (competitionUpdate) {
console.log(competitionUpdate);
return competitionUpdate;
});
Q: What am i doing wrong here, and why can it create a conflict?
I was trying to accomplish the same thing in my recent project and got the same error. I solved my problem using two queries
First, let find the User is present and store the result
let result = Competition_global.findOne(
{"competitors.userid": user._id, _id: globalCompetition._id}
});
By using the result if the user not found then push the new user object in the competitors array
if (result === null) {
let result = await Competition_global.insertOne(
{
$push: {
// your new user data
},
}
);
}
else Update the user amount
else {
let result = await Competition_global.updateOne(
{"competitors.userid": user._id, _id: globalCompetition._id},
{
$inc: {"competitors.$.amount": amount},
}
);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With