[英]Insert inner a deep document in MongoDB with Node.js
I'm trying to insert a city into a states array inner a country array, it is a bit confusing for me. 我试图将一个城市插入一个国家数组内的一个states数组,这对我来说有点令人困惑。 I'm using MEAN.
我正在使用MEAN。 This is the MongoDB model:
这是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}]
}]
}]
};
When I insert a new City, I need update cities
inner states
and push another one. 插入新城市时,我需要更新
cities
内部states
并推送另一个states
。
I'm using POST metod, and this looks like this: 我正在使用POST方法,它看起来像这样:
api.post('/city/', wagner.invoke(function (Location) { return function (req, res) { return require('./Controllers/locationController').newCity(req, res, Location); }; }));
And is this newCity
function: 并且是这个
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}) }); };
Most probably that the query on the update function is misconceived. 最有可能是关于更新函数的查询被误解了。
I'm sending the following JSON as a request: 我正在发送以下JSON作为请求:
{ "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
}
}
I solved my problem with projection operator
, I didn't know it, but I researched. 我用
projection operator
解决了问题,我不知道,但我进行了研究。
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});
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.