始终populate()
您的词汇模式中的某些字段
在这里阅读文档。
注意:人口是一个强大的功能,但它具有局限性,可以帮助您摆脱差的模式设计。特别是,通常是包含在文档中没有绑定的阵列的数组,通常是不良的MongoDB模式设计。在模式中不包含不断增长的objectID数组 - 随着阵列的增长,您的数据将变得笨拙,最终您将达到16 MB的文档尺寸限制。通常,在设计模式时仔细考虑。
mongoose-autopopulate
模块公开了一个单个功能,您可以将其传递给Mongoose Schema的plugin()
函数。
const schema = new mongoose . Schema ( {
populatedField : {
type : mongoose . Schema . Types . ObjectId ,
ref : 'ForeignModel' ,
// The below option tells this plugin to always call `populate()` on
// `populatedField`
autopopulate : true
}
} ) ;
schema . plugin ( require ( 'mongoose-autopopulate' ) ) ;
仅将此插件应用于顶级模式。不要将此插件应用于儿童模式。
// Don't do `nestedSchema.plugin(require('mongoose-autopopulate'))`.
// You only need to add mongoose-autopopulate to top-level schemas.
const nestedSchema = mongoose . Schema ( {
child : { type : Number , ref : 'Child' , autopopulate : true }
} ) ;
const topSchema = mongoose . Schema ( { nested : nestedSchema } ) ;
topSchema . plugin ( require ( 'mongoose-autopopulate' ) ) ;