最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 6浏览 0评论

在填充后钩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');
});
发布评论

评论列表 (0)

  1. 暂无评论