mongodb - Conditionally increment field(s) using upsert

62lalag4  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(95)

我正在尝试插入/更新(upsert)文档。
在下面的代码中,这一行在语法上是不正确的,但这正是我正在尝试做的:

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

如果类型(传入req.body)为profileCompletion,我希望文档为

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

这里是我现在的查询

await db.collection('emails')

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

93ze6v8z1#

您可以先建立更新对象,再将它传递给查询:

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

相关问题