Mehrnoosh
Mehrnoosh

Reputation: 899

update if exist insert if it doesn't exist for sub docs in mongoose

I see every relevant links for my data there is not a proper solution. My Schema is like this:

{
"_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
    }
]
}

I want to add a country like this:

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

if it does exist just update it from false to true or vise versa, otherwise insert the new object.

I write code for it but it seems long story and also it is not working correctly in insert mode(get this error : The positional operator did not find the match needed from the query). I would be grateful for any helps ....

    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
    });

  });

Upvotes: 0

Views: 709

Answers (1)

Shantanu Madane
Shantanu Madane

Reputation: 615

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);
                  } 
               });
           }
        });

    },

Upvotes: 1

Related Questions