【问题标题】:How do I $cond a $push/$pull in a MongoDB update with upsert:true如何使用 upsert:true 在 MongoDB 更新中 $cond $push/$pull
【发布时间】:2016-09-22 08:10:42
【问题描述】:

我正在尝试根据条件以及 upsert 进行推送或拉取

    myCollection.update(
  {'id': location},
  {
    $set: { count },
    $setOnInsert: {
      id: location,
      users: []
    },
  },
  {
    $cond: {
      if: (increment==1),
      then: {$push: { users: userToken }},
      else: {$pull: { users: userToken }}
    }
  },
  {'upsert':true},
  (err, data) => {
    ...

我正在尝试把它弄干(这很有效):

    mongo.connect(dbUrl, (err, db) => {
if (err) throw err
let myCollection = db.collection('myCollection')
if(increment==1){
  myCollection.update(
    {'id': location},
    {
      $set: { count },
      $push: { users: userToken },
      $setOnInsert: {
        id: location
      }
    },
    {'upsert':true},
    (err, data) => {
      if (err) throw err
      console.log(data);
      callback()
      db.close()
    }
  )
}
else{
  myCollection.update(
    ...
    $pull: { users: userToken },
    ...
  )
}

})

当我有 $cond 时,它不会向数据库添加任何内容。 $cond 应该在哪里?

【问题讨论】:

    标签: javascript node.js mongodb conditional


    【解决方案1】:

    $cond 在这里不适用,但在聚合框架中。您需要的是一个纯旧的原生 JS 条件语句,在更新操作中使用它之前创建更新文档,当然这应该在条件块中设置。考虑以下示例:

    let queryObj = { 'id': location },
        usersObj = { 'users': userToken },
        updateObj = { 
            '$set': { count },
            '$setOnInsert': queryObj
        },
        options = { 'upsert': true },
        updateOperator = '$pull';
    
    if (increment == 1) updateOperator = '$push';
    updateObj[updateOperator] = usersObj;
    
    myCollection.update(queryObj, updateObj, options,
        (err, data) => {
            if (err) throw err
            console.log(data);
            callback();
            db.close();
        }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-01
      相关资源
      最近更新 更多