Home > Blockchain >  mongodb - Conditionally increment field(s) using upsert
mongodb - Conditionally increment field(s) using upsert

Time:10-26

I am trying to insert/update (upsert) a document.

In the code below, this line is syntactically incorrect but that is what I am trying to do:

     $inc: { {type=="profileCompletion"?"profileCompletion":"matchNotification"}: 1},

If type (passed in req.body) is profileCompletion, I want document to be

    {
        "_id": "0h4wpbgy7u",
        "date": "Oct242022",
        "profileCompletion": 1,
        "matchNotification": 0
    }

Here the the query I have now

    await db.collection('emails')
 

       .updateOne(
          {
          _id: userId
          },
          {
            $setOnInsert: 
              {
                time: getDateMonYear(new Date()),
              },
            $inc: { {type=="profileCompletion"?"profileCompletion":"matchNotification"}: 1},
          },
          {upsert: true},
        )

CodePudding user response:

You can build the update object before passing it to the query:

const update = { $setOnInsert: { time: getDateMonYear(new Date()) }};

if (type === 'profileCompletion') {
  update.$inc = { profileCompletion: 1 }; 
} else {
  update.$inc = { matchNotification: 1 }; 
}

...

await db.collection('emails').updateOne({ _id: userId }, update, { upsert: true });
  • Related