Mongoose无法populate深度子文档sheets.deales.crew如何解决
Mongoose深度子文档populate失败问题解决
核心错误点
refPath使用错误:refPath的作用是指向当前文档的某个字段值作为关联的模型名,你此处要关联Crew模型直接用ref即可,填写refPath: 'Guild.crews'属于语法错误,导致populate逻辑完全失效返回空数组。- 字段类型判断错误:
dealSchema中crew字段定义为数组类型,你测试代码直接判断数组本身存在name属性,本身就不符合逻辑。 - 嵌套populate写法不规范:多层嵌套子文档的populate最好显式指定层级,避免旧版本Mongoose识别异常。
- 冗余定义子文档模型:内嵌在父文档里的子Schema不需要单独创建模型,你定义的
SheetModel、DealModel、CrewModel完全多余,反而会干扰关联逻辑。
修正后的Schema代码
// 子Schema要定义在父Schema之前 const crewSchema = new Schema<Crew>({ name: { type: String, required: true }, }); const dealSchema = new Schema<Deal>({ // 替换refPath为ref,如果业务上crew是单对象就去掉数组括号 crew: { type: Schema.Types.ObjectId, ref: 'Guild.crews' }, damage: { type: Number, required: true }, }) const sheetSchema = new Schema<Sheet>({ deales: [dealSchema] }) const guildSchema = new Schema<Guild>({ sheets: [sheetSchema], crews: [crewSchema], }); const GuildModel= getModel('Guild', guildSchema) // 不需要单独定义内嵌子文档的Model
修正后的测试代码
it("populated guild.sheets.deales.crew must have name",async () => { const guild = await GuildModel.findOne({}) .populate({ path: 'sheets', populate: { path: 'deales', populate: { path: 'crew' } } }) // 如果业务上crew确实是数组类型,此处改为取数组第一个元素判断:guild.sheets[0].deales[0].crew[0] expect(guild.sheets[0].deales[0].crew).to.has.property("name") })
额外注意事项
如果使用Mongoose 6+版本,execPopulate已经废弃,不需要调用,直接await guild.populate(...)即可完成填充。同时要确认数据库中存储的crew字段ObjectId确实存在于对应公会的crews数组中,否则populate也会返回空值。
内容的提问来源于stack exchange,提问作者BAN IP
相关产品推荐
相关产品推荐

