2015-09-04 129 views
0

有沒有辦法填充全部運行貓鼬查詢時的字段,以防您事先不知道哪些字段是引用的文檔?類似這樣的:填寫貓鼬的所有領域?

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

你做CA測試的,如果你用,'貓鼬,autopopulate',只是如果你有機會到架構。 – Rudra

+0

感謝不幸的是,儘管如此,它只適用於在模式中添加'autopopulate:true'的字段。但看看它的代碼,我想我可能會創建一個真正自動填充所有字段的類似插件 – laggingreflex

+1

這似乎是一個非常可疑的事情要做。人口很貴,只能根據需要進行。 – JohnnyHK

回答

3

我寫了一個小插件。它遍歷模式,並查找具有ref屬性的字段,並將它們添加爲在預先查找鉤子中輸入到.populate()的路徑。與貓鼬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*/} } ]