微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我有下面的猫鼬模式,

 

    {
      "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 举报,一经查实,本站将立刻删除。