Alejandro Rt Alejandro Rt - 1 month ago 19
Node.js Question

Insert inner a deep document in mongodb with nodejs

I'm trying to insert a city into a states array inner a country array, it is a bit confused for me. I'm using MEAN. This is the mongodb model:

var countrySchema = {
countryName: { type: String, required: true },
loc: [{ type: Number, required: true }],
states: [{
stateName: { type: String, required: true },
loc: [{ type: Number, required: true }],
cities: [{
cityName: { type: String, required: true },
loc: [{type: Number, required: true}]
}]
}]
};


When I insert a new City, I need update
cities
inner
states
and push other one.

I'm using POST metod, and this looks like this:


api.post('/city/', wagner.invoke(function (Location) {
return function (req, res) {
return require('./Controllers/locationController').newCity(req, res, Location);
};
}));



And is this
newCity
function:


module.exports.newCity = function (req, res, Location) {
try {
var locations = req.body.locations;
} catch (error) {
return res.status(status.BAD_REQUEST).json({error: error.toString()});
}
Location.update({"countryName": locations.countryName, "states.stateName": locations.states.stateName}, {'$push': {'cities': locations.states.cities}}, function (error, city) {
if (error) {
return res.status(status.INTERNAL_SERVER_ERROR).json({error: error.toString()});
}
if (!city) {
return res.status(status.NOT_FOUND).json({error: error.toString()});
}
res.json({city: city})
});
};



Most probably that the query on the update function is misconceived.

I'm send the follow JSON as request:


{
"locations": {
"countryName": "Mexico",
"loc": [1, 2],
"states": {
"stateName": "test one",
"loc": [1, 2],
"cities": {
"cityName": "City for test one",
"loc": [1, 2]
}
}
}
}



And I get this response:

{
"city": {
"ok": 0
"n": 0
"nModified": 0
}
}

Answer

I solved my problem with projection operator, I didn't know it, but I researched.

The solution looks like that:

module.exports.newCity = function (req, res, Location) {
    try {
        var locations = req.body.locations;
    } catch (error) {
        return res.status(status.BAD_REQUEST).json({error: error.toString()});
    }
    Location.update({
        "countryName": locations.countryName,
        'states.stateName': locations.states.stateName
    }, {
        '$push': {
            'states.$.cities': locations.states.cities
        }
    }, function (error, city) {
        if (error) {
            return res.status(status.INTERNAL_SERVER_ERROR).json({error: error.toString()});
        }
        if (!city) {
            return res.status(status.NOT_FOUND).json({error: error.toString()});
        }
        res.json({city: city});
    });
};
Comments