未将填充到父文档refs数组后的Mongoose文档填充

时间:2017-07-24 15:41:23

标签: node.js mongodb mongoose mongoose-schema mongoose-populate

我有这样的事情:

let fooSchema = new mongoose.Schema({
    bars: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Bar' }],
});

let barSchema = new mongoose.Schema({
    sth1: String,
    sth2: String,
    sth3: String,
});

两个模式都在单独的文件中并导出为mongoose模型。

所以我有一个foo文档,其中包含空bars数组和一个bar文档,例如:

let foo = new Foo({ bars: [] });
let bar = new Bar({ sth1: "1", sth2: "2", sth3: "3" });

然后,当我将bar推入foo s bars并控制台记录此数组时,我得到了:

foo.bars.push(bar);
console.log(foo.bars);
//it outputs:
["59760dcbe3a7e31c2693ce47"]

所以foo.bars只有ids。 我该怎么做才能在这个数组中包含整个文档(不保存,然后查找并填充此字段)?

我想要实现的目标是:

foo.bars.push(bar);
console.log(foo.bars);
[{ _id: 59760dcbe3a7e31c2693ce47, sth1: "1", sth2: "2", sth3: "3" }]

1 个答案:

答案 0 :(得分:0)

您正在使用人口,但听起来您想使用sub documents

let barSchema = new mongoose.Schema({
    sth1: String,
    sth2: String,
    sth3: String,
});

let fooSchema = new mongoose.Schema({
    bars: [ barSchema ]
});

由于barSchema没有关联模型,因此您无法实例化bar个文档。你可以使用这样的东西:

let foo = new Foo({ bars: [ { sth1: "1", sth2: "2", sth3: "3" } ] });

或者:

let foo = new Foo;
foo.bars.create({ sth1: "1", sth2: "2", sth3: "3" });