更新如果存在插入,如果它不存在于mongoose中的子文档

时间:2017-05-09 08:36:30

标签: mongodb mongoose

我看到我的数据的每个相关链接都没有正确的解决方案。 我的架构是这样的:

{
"_id" : ObjectId("590aa0e68d4b23760d8d0e50"),
"updatedAt" : ISODate("2017-05-08T07:03:08.314Z"),
"createdAt" : ISODate("1987-12-31T16:00:00.000Z"),
"Avatar" : "public/image/test.pic",
"countries" : [ 
    {
        "code" : "MY",
        "is_favourite" : false,
        "is_visited" : true,
    },
    {
        "code" : "CA",
        "is_favourite" : true
    }
]
}

我想添加一个这样的国家:

{
   "code" : "QC",
   "is_favourite" : true
}

如果确实存在,只需将其从false更新为true,反之亦然,否则插入新对象。

我为它编写代码,但它看起来很长,而且在插入模式下也无法正常工作(得到此错误:位置操作符未找到查询所需的匹配项)。我会感激任何帮助......

    var query = {"_id":req.params._id, "countries":{$elemMatch:{code:req.body.code}}}
    var update = { $set: {"countries.$.is_favourite": req.body.is_favourite}}
    var option = {"upsert": true}

  User.findOneAndUpdate(query,update,option, function (err, user) {

    if (err) return next(err);
    return res.status(201).json({
      success: true,
     message: 'country '+ '<'+req.body.code+'> '+ 'updated as ' 
 +req.body.is_favourite
    });

  });

1 个答案:

答案 0 :(得分:1)

This is what i have tested and works perfectly as expected.
Logic is pretty clear you just need to make small changes.


updateTestTable: function (req, res, callback) {
        var pushData = {
            "code": "QC",
            "is_favourite": true
        };
        console.log("INSIDE");
        var objectID=new mongoose.Types.ObjectId("59119107fd4790422fcb676a");
        test.findOne({"_id":objectID,"countries.code":pushData.code},function(err,data){
           console.log(JSON.stringify(data));
           if(data!==null){
               //Update Data
               console.log("HELLO");
               test.findOneAndUpdate({"_id":objectID,"countries.code":pushData.code},{ $set: { "countries.$.is_favourite": false} },function(err,data){
                   if(data){
                       console.log("DATA UPDATED");
                       console.log(data);
                   }
                   else{
                       console.log("ERR",err);
                   }
               });

           }
           else{
               //Insert Data
               test.findOneAndUpdate({"_id":objectID},{$push: {countries: pushData }},function(err,data){
                  if(data){
                      console.log("DATA INSERTED");
                      console.log(data);
                  } 
               });
           }
        });

    },