Mongoose填充对象ID数组

时间:2017-05-29 05:43:42

标签: node.js mongodb mongoose mongoose-populate

我正在尝试使用与该特定线程相关的所有注释来填充我的线程模式GET响应。我在Thread模型中指定了一个路径来接受一个Comments数组,然后我会在请求一个线程时填充它,但它仍然是空的。

我不确定我是否需要将所有注释都推送到线程中,但我认为按照我的方式,它不是必需的?我正在使用Mongoose 4.4.19。我跟着文档一直跟着,但仍然无法弄清楚我哪里出错了。

线程架构:

const threadSchema = new Schema({
    user: {
        type: Schema.ObjectId,
        ref: 'User',
        required: true
    },
    title: {
        type: String
    },
    content: {
        type: String
    },
    category: {
        type: String
    },
    comments: [{
        type: Schema.ObjectId,
        ref: 'Comment'
    }]
}, {
    timestamps: true
})

评论架构:

const commentSchema = new Schema({
  user: {
    type: Schema.ObjectId,
    ref: 'User',
    required: true
  },
  thread: {
    type: Schema.ObjectId,
    ref: 'Thread',
    required: true
  },
  content: {
    type: String
  }
}, {
  timestamps: true
})

处理获取请求:

export const index = ({ querymen: { query, select, cursor } }, res, next) =>
  Thread.find(query, select, cursor)
    .populate('user comments')
    .then(threads => threads.map(thread => thread.view()))
    .then(success(res))
    .catch(next)

0 个答案:

没有答案
相关问题