【问题标题】:Embedded document not saved to its collection嵌入文档未保存到其集合中
【发布时间】:2012-05-11 00:43:53
【问题描述】:

似乎我的嵌入文档没有保存到它们各自的集合中。这是我的模型:

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 集合中。

我做错了什么?

【问题讨论】:

  • country.name 应为continent.name。
  • 你能发布 db.continent.find() 的输出吗?将有助于答案

标签: node.js mongodb mongoose


【解决方案1】:

这可能太简单了,但您只调用了continent.save(),而不会在for 循环结束时调用county.save() 或country.save()。这只是一个遗漏还是可以解决问题。如果有遗漏,请参阅我关于发布输出的说明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多