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

问题描述

我有下面的猫鼬模式,

 

    {
      "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在单个查询中插入和更新字段的解决方案?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)