我有这样的事情:
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" }]
答案 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" });