2012-05-10 38 views
1

看起来好像我的嵌入文档没有被保存到它们各自的集合。这里是我的模型:嵌入文档没有保存到它的集合

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(),什么都没有回来。所以看起来好像县和国家文件没有被保存到数据库到它们各自的集合,而是作为常规属性(而不是嵌入式文档)保存到大陆集合。

我在做什么错?

+0

country.name应该读取continent.name。 – tremolo

+0

你可以发布db.continent.find()的输出吗?将有助于答案 –

回答

1

这可能太简单了,但您只是调用continent.save(),并且从不在调用循环的末尾调用county.save()或country.save()。这只是一个疏忽或者是否解决了这个问题。如果这是一个遗漏,请参阅我关于发布输出的说明。

+0

谢谢,这就是诀窍! – tremolo

相关问题