[英]Insert inner a deep document in MongoDB with Node.js
我试图将一个城市插入一个国家数组内的一个states数组,这对我来说有点令人困惑。 我正在使用MEAN。 这是MongoDB模型:
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}]
}]
}]
};
插入新城市时,我需要更新cities
内部states
并推送另一个states
。
我正在使用POST方法,它看起来像这样:
api.post('/city/', wagner.invoke(function (Location) { return function (req, res) { return require('./Controllers/locationController').newCity(req, res, Location); }; }));
并且是这个newCity
函数:
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}) }); };
最有可能是关于更新函数的查询被误解了。
我正在发送以下JSON作为请求:
{ "locations": { "countryName": "Mexico", "loc": [1, 2], "states": { "stateName": "test one", "loc": [1, 2], "cities": { "cityName": "City for test one", "loc": [1, 2] } } } }
我得到这个回应:
{
"city": {
"ok": 0
"n": 0
"nModified": 0
}
}
我用projection operator
解决了问题,我不知道,但我进行了研究。
解决方案如下所示:
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});
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.