猫鼬更新对象值数组(如果存在),否则在单个查询中推送对象

时间:2020-10-14 20:56:24

标签: javascript mongodb mongoose insert-update

我有下面的猫鼬模式,

 

    {
      "name": "String",
      "code": "String",
      "publish": {
        "status": 1,
        "channels": [
          {
            "_id": false,
            "channelId": "Number",
            "remoteId": "String"
          }
        ]
      }
    }

如果remoteIdchannelId字段值匹配,我尝试更新name值,否则将channelIdremoteId值推送到{ {1}}数组。

我尝试了以下代码段,但未更新该值。


    const setFields = { publish: { channels: { 1 } } }
    
      Categories.updateOne(
        { name: 'Pantlooms', "publish.channels.channelId": channelId },
        { $set: setFields, $addToSet: { channels: { remoteId: "12" } } },
        { upsert: true }
      )

   

    Categories.update({
        name: 'Pantlooms'
      },
        {
          $set: {
            "publish": {
              $cond: {
                if: { $eq: ["channels.$.channelId", 1] },
                then: { channels: [{ remoteId: "12"}] },   // it's the upsert case
                else: { channels: [{ channelId: 1, remoteId: "12" }] }    // it's the update case
              }
            }
          }
        },
        {
          upsert: true
        })

我什至尝试使用channels,但它仅用于推送不存在但不更新channelId的值。

      let conditions = { 
         "name": "Pantlooms",
         "publish.channels.channelId": {
            "$nin": [1]
         }
      };
    
      var update = {
        $addToSet: { publish: { channels: { channelId: 1, remoteId: "12" } } }
      }
    
      Categories.findOneAndUpdate(conditions, update, function (err, doc) {
        console.log(err);
      });
    

是否存在使用Mongoose在单个查询中插入和更新字段的解决方案?

0 个答案:

没有答案
相关问题