embedded式文档未保存到其集合中

好像我的embedded式文档没有被保存到它们各自的集合中。 这是我的模型:

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(),什么都没有回来。 因此,似乎县和国家文件没有被保存到数据库到他们各自的集合,而是保存到大陆集合作为常规属性,而不是embedded式文件。

我究竟做错了什么?

这可能太简单了,但是你只需要调用continent.save(),而不要在for循环结尾调用county.save()或country.save()。 这只是一个疏忽或者是否解决了这个问题。 如果这是一个遗漏,请参阅我关于张贴输出的说明。