在填充后钩middlewhere的“查找”中猫鼬
我有贴在我的网站用户文章的文章架构。它引用的用户集合:
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'
}
});
我想有一个职位挂钩上的所有查找/ findOne调用来填充参考:
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');
});
在填充后钩middlewhere的“查找”中猫鼬
我有贴在我的网站用户文章的文章架构。它引用的用户集合:
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'
}
});
我想有一个职位挂钩上的所有查找/ findOne调用来填充参考:
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');
});