看起來好像我的嵌入文檔沒有被保存到它們各自的集合。這裏是我的模型:嵌入文檔沒有保存到它的集合
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()的輸出嗎?將有助於答案 –