我有贴在我的网站用户文章的文章架构。它引用的用户集合:
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');
});
因为他们在明年没有要求终止预钩中间件上面的回答可能无法正常工作。正确的实现应该
productSchema.pre('find', function (next) {
this.populate('category','name');
this.populate('cableType','name');
this.populate('color','names');
next();
});
查询中间件,中间件文件不同的微妙但重要的途径:在文档中间件,这是指被更新的文件。在查询中间件,猫鼬不必到文档中的引用进行更新,所以这是指查询对象,而不是文件被更新。
我们不能从后发现里面的中间件修改的结果,因为这是指查询对象。
TestSchema.post('find', function(result) {
for (let i = 0; i < result.length; i++) {
// it will not take any effect
delete result[i].raw;
}
});