【问题标题】:Mongoose document after pushing it to parent document refs array is not populated将 Mongoose 文档推送到父文档 refs 数组后未填充
【发布时间】:2017-07-24 23:53:48
【问题描述】:

我得到了这样的东西:

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

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

两种模式都在单独的文件中,并作为猫鼬模型导出。

所以我有一个带有空bars 数组的foo 文档和一个bar 文档,例如:

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

然后,当我将 bar 推入 foos bars 并控制台记录这个数组时,我得到了:

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

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

我想要实现的是:

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

【问题讨论】:

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


    【解决方案1】:

    您正在使用人口,但听起来您想使用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" });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-21
      • 2017-06-06
      • 2014-08-06
      • 1970-01-01
      • 2017-01-27
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      相关资源
      最近更新 更多