lag*_*lex 3 mongoose mongodb node.js
有没有办法在运行mongoose查询时填充所有字段,以防您事先不知道哪些字段是引用的文档?像这样的东西:
schema = new Schema({ ref: {type:ObjectId, ref:'ref'}});
db = Model('data', schema);
db.find({}).populate('*').
// or
db.find({}).populate({path:'*'}).
//=> {ref: {_id:...,}} // "ref" is populated automatically
Run Code Online (Sandbox Code Playgroud)
我写了一个小插件.它遍历模式并查找具有ref属性的字段,并将它们添加为.populate()在预查找挂钩中提供的路径.用Mongoose v4测试
function autoPopulateAllFields(schema) {
var paths = '';
schema.eachPath(function process(pathname, schemaType) {
if (pathname=='_id') return;
if (schemaType.options.ref)
paths += ' ' + pathname;
});
schema.pre('find', handler);
schema.pre('findOne', handler);
function handler(next) {
this.populate(paths);
next();
}
};
module.exports = autoPopulateAllFields;
Run Code Online (Sandbox Code Playgroud)
var articleSchema = new Schema({
text: {type: 'String'},
author: {type: 'ObjectId', ref: 'user'}
});
articleSchema.plugin(autoPopulateAllFields);
var Article = mongoose.model('article', articleSchema);
Run Code Online (Sandbox Code Playgroud)
Article.find({}) => [ {text:..., author: { _id:..., name:... /*auto-populated*/} } ]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2997 次 |
| 最近记录: |