简体   繁体   中英

i can't populate mongoose deep subdocument

Below is the code that simplified the model and schema I'm having a hard time with

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)

and this is Mocha-chai testcode what always throw exception

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'
})

None of the answers on stackoverflow solved my problem. I wasted 5 hours on just a few lines of this code. please help me

You checked this? https://github.com/Automattic/mongoose/issues/1377#issuecomment-15911192

This person changed nested code

    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);

from this

      var authors = docs.map(function(doc) {
        return doc.author;
      });

      User.populate(authors, {
        path: 'phone',
        select: 'name'
      }, callback);

to this.

author(User)is in BlogPost. BlogPost Schema has just User ObjectId, so can't understand author.phone

I might have already checked it, but I'm uploading it just in case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM