我无法填充猫鼬深层子文档

时间:2021-06-13 14:56:04

标签: javascript node.js typescript mongodb mongoose

下面是简化我遇到困难的模型和架​​构的代码

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 个小时。请帮帮我

1 个答案:

答案 0 :(得分:-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 Schema只有User ObjectId,所以看不懂author.phone

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