8

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?

6
  • Try removing amount key in the newInsertMent object. As the error states, that amount field will create a conflict with the subsequent "competitors.$.amount" update.
    – chridam
    Feb 19, 2018 at 10:41
  • @chridam good idea. unfortunly its still a conflict.
    – maria
    Feb 19, 2018 at 11:03
  • How about using $set with the positional operator i.e. { $set: {"competitors.$.reward": newInsertMent.reward }, $inc: {"competitors.$.amount": amount}},?
    – chridam
    Feb 19, 2018 at 11:06
  • @chridam still conflict
    – maria
    Feb 19, 2018 at 11:07
  • with a rewrite in set, i get: MongoError: The positional operator did not find the match needed from the query.@chridam
    – maria
    Feb 19, 2018 at 11:09

2 Answers 2

1

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

0

This is a known issue #7003 of mongoose (and may be mongodb)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.