似乎我的嵌入文档没有保存到它们各自的集合中。这是我的模型:
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(),则不会返回任何内容。因此,似乎 County 和 Country 文档没有被保存到数据库中各自的集合中,而是作为常规属性保存到 Continent 集合中(而不是嵌入文档)。
我究竟做错了什么?