我试图将一个城市插入国家/地区阵列内的状态数组中,这对我来说有点混乱。我使用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
并推送另一个。
我正在使用POST metod,这看起来像这样:
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
}
}
答案 0 :(得分: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});
});
};