看起来好像我的嵌入文档没有被保存到它们各自的集合。这里是我的模型:嵌入文档没有保存到它的集合
var County = new Schema({
_id : Schema.ObjectId,
name : String,
biggestCity : String
});
var Country = new Schema({
_id : Schema.ObjectId,
name : String,
counties : {type: [County], ref: "County"}
});
var Continent = new Schema({
_id : Schema.ObjectId,
countries : {type: [Country], ref: "Country"},
});
...这是我用来保存到MongoDB的代码:
var continentModel = mongoose.model("Continent");
var continent = new continentModel();
country.name = name;
var countryModel = mongoose.model("Country");
var countyModel = mongoose.model("County");
for (var i = 0; i < req.body.countries.length; i++) {
var country = new countryModel();
country.name = req.body.countries[i].name;
for (var j = 0; j < req.body.countries[i].counties.length; j++) {
var county = new countyModel();
county.name = req.body.countries[i].counties[j].name;
county.biggestCity = req.body.countries[i].counties[j].biggestCity;
countries.counties.push(county);
}
continent.countries.push(country;
}
continent.save();
如果我做了db.continents.find(),文档回来与所有物业(包括国家和县)居住。
但是,如果我做了一个db.counties.find()或db.countries.find(),什么都没有回来。所以看起来好像县和国家文件没有被保存到数据库到它们各自的集合,而是作为常规属性(而不是嵌入式文档)保存到大陆集合。
我在做什么错?
country.name应该读取continent.name。 – tremolo
你可以发布db.continent.find()的输出吗?将有助于答案 –