【问题标题】:i can't populate mongoose deep subdocument我无法填充猫鼬深层子文档
【发布时间】:2021-08-29 17:31:36
【问题描述】:

下面是简化模型和架构的代码,我很难使用

const guildSchema = new Schema<Guild>({
    sheets: [sheetSchema],
    crews: [crewSchema],
});
const GuildModel= getModel('Guild', guildSchema)

const sheetSchema = new Schema<Sheet>({
    deales: [dealSchema]
})
const SheetModel = getModel('Guild.sheets', sheetSchema)

const dealSchema = new Schema<Deal>({
    crew: [{ type: Schema.Types.ObjectId, refPath: 'Guild.crews' }],
    damage: { type: Number, required: true },
})
const DealModel = getModel('Guild.sheets.deales', dealSchema)

const crewSchema = new Schema<Crew>({
    name: { type: String, required: true },
})
const CrewModel= getModel('Guild.crews', crewSchema)

这是 Mocha-chai 测试代码,总是抛出异常

it("populated guild.sheets.deales.boss must have name",async () => {
    const guild = await GuildModel.findOne({})
    await guild.populate({
        path: 'sheets.deales.crew'
    }).execPopulate()
    
    expect(guild.sheets[0].deales[0].crew).to.has.property("name") // expected [] to have property 'name'
})

stackoverflow 上的答案都没有解决我的问题。我在这几行代码上浪费了 5 个小时。请帮帮我

【问题讨论】:

    标签: javascript node.js typescript mongodb mongoose


    【解决方案1】:

    你检查过这个吗? https://github.com/Automattic/mongoose/issues/1377#issuecomment-15911192

    此人更改了嵌套代码

        var opts = {
            path: 'author.phone',
            select: 'name'
          };
    
          BlogPost.populate(docs, opts, function (err, docs) {
            assert.ifError(err);
            docs.forEach(function (doc) {
              console.log(doc);
            });
            callback(null);
    

    从这里

          var authors = docs.map(function(doc) {
            return doc.author;
          });
    
          User.populate(authors, {
            path: 'phone',
            select: 'name'
          }, callback);
    

    到这个。

    作者(用户)在 BlogPost 中。 BlogPost Schema 只有 User ObjectId,所以无法理解 author.phone

    我可能已经检查过了,但我上传它以防万一。

    【讨论】:

      猜你喜欢
      • 2017-05-07
      • 2021-02-11
      • 2021-10-07
      • 2016-08-17
      • 2015-11-27
      • 2015-07-28
      • 2020-11-09
      • 2015-02-09
      • 2021-04-26
      相关资源
      最近更新 更多