始終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' ) ) ;