在填充后钩middlewhere的“查找”中猫鼬

问题描述 投票:1回答:3

我有贴在我的网站用户文章的文章架构。它引用的用户集合:

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对象,而不是在文档级别来填充?

node.js mongodb mongoose middleware mongoose-populate
3个回答
2
投票

这是因为populate是查询对象的方法,而不是文件。您应该使用pre钩代替,就像这样:

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

1
投票

因为他们在明年没有要求终止预钩中间件上面的回答可能无法正常工作。正确的实现应该

productSchema.pre('find', function (next) {
this.populate('category','name');
this.populate('cableType','name');
this.populate('color','names');
next();

});


0
投票

MongooseJS Doc

查询中间件,中间件文件不同的微妙但重要的途径:在文档中间件,这是指被更新的文件。在查询中间件,猫鼬不必到文档中的引用进行更新,所以这是指查询对象,而不是文件被更新。

我们不能从后发现里面的中间件修改的结果,因为这是指查询对象。

TestSchema.post('find', function(result) {
  for (let i = 0; i < result.length; i++) {
    // it will not take any effect
    delete result[i].raw;
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.