在post hook中间填充mongoose中的'find'

我有用户发布在我的网站上的文章的文章架构。 它引用了用户集合:

var ArticleSchema = new Schema({ title: { // NO MARKDOWN FOR THIS, just straight up text for separating from content type: String, required: true }, author: { type: Schema.Types.ObjectId, ref: 'User' } }); 

我想在所有find / findOne调用上有一个post钩子来填充引用:

 ArticleSchema.post('find', function (doc) { doc.populate('author'); }); 

出于某种原因,在钩子中返回的文档没有填充方法。 我是否必须使用ArticleSchema对象而不是文档级别填充?

这是因为populate是查询对象的一种方法,而不是文档。 你应该使用一个pre钩子,而不是像这样:

 ArticleSchema.pre('find', function () { // `this` is an instance of mongoose.Query this.populate('author'); }); 

来自MongooseJS文档 :

查询中间件与文档中间件有着微妙而重要的区别:在文档中间件中,这是指正在更新的文档。 在查询中间件中,mongoose不一定具有对被更新文档的引用,所以这是指查询对象而不是被更新的文档。

我们不能修改后查找中间件的结果 ,因为是查询对象。

 TestSchema.post('find', function(result) { for (let i = 0; i < result.length; i++) { // it will not take any effect delete result[i].raw; } });