简体   繁体   中英

Push data in nested arrays nodeJs, MongoDB

I Have Document Like,

{
    "_id" : ObjectId("5ab4cc12c773133bae3d8dc9"),
    "__v" : 19.0,
    "geoGraphicalFilter" : {
        "aCountries" : [
            {
                "country" : "Spain",
                "_id" : ObjectId("5ad49ab21210c42aa6ccba23"),
                "cities" : [ ]
            },
            {
                "country" : "India",
                "_id" : ObjectId("5ad49ab21210c42aa6ccba24"),
                "cities" : [ ]
            }
        ]
    }
}

Model

const HuntingWindow = new Schema({
  geoGraphicalFilter: {
    aCountries: [
      {
        country: String,
        cities: { type: Array }
      }
    ]
  },
});

Snippet

const addCityFilter = (req, res) => {
  if (req.body.aCities === "") {
    res.status(409).jsonp({ message: adminMessages.err_fill_val_properly });
    return false;
  } else {
    var Cities = req.body.aCities.split(",");
    huntingModel.update({ _id: req.body.id,"data.geoGraphicalFilter.aCountries":req.body.sName },
    {$push:{"geoGraphicalFilter.0.aCountries.$.cities":Cities}},
    (error, data) => {       
        // Cities.forEach(element => {
        //   data.geoGraphicalFilter.aCountries.find(req.body.sName)
        // });
      data.save((error, success) => {
        res.status(200).jsonp({
          message: adminMessages.succ_countryFilter_added
        });
      });
    });
  }
};

Now I want to first Find Document by root id and then I want to match the country name and insert the cities in the Array. I am new to MongoDB and nodejs how can i do this ? While i am trying to with update query but i thing i am doing it on wrong way plese help me with it.

Try following code:

huntingModel.update(
    { _id: ObjectId("5ab4cc12c773133bae3d8dc9"), "geoGraphicalFilter.aCountries.country": "Spain"  },
    { $addToSet: { "geoGraphicalFilter.aCountries.$.cities": { $each: [ "city1", "city2" ] } } }
)

You should specify two filtering conditions: one for entire document and one to match array element. Then you can use $ operator to update first matching document in that array. To push multiple values you can use $each operator. To ensure that there will be no duplicates you should use $addToSet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM