Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb Updating the path would create a conflict

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?

like image 441
maria Avatar asked Feb 19 '18 10:02

maria


1 Answers

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},
      }
    );
  }
});

like image 98
Pursharth Vohra Avatar answered Sep 19 '22 10:09

Pursharth Vohra