填充mongoose中的所有字段?

时间:2015-09-04 22:10:15

标签: node.js mongodb mongoose

有没有办法在运行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

1 个答案:

答案 0 :(得分:5)

我写了一个小插件。它遍历模式并查找具有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;
var articleSchema = new Schema({
    text: {type: 'String'},
    author: {type: 'ObjectId', ref: 'user'}
});
articleSchema.plugin(autoPopulateAllFields);
var Article = mongoose.model('article', articleSchema);
Article.find({}) => [ {text:..., author: { _id:..., name:... /*auto-populated*/} } ]