【发布时间】:2018-06-26 19:11:10
【问题描述】:
所以我有 Story 和 Comment 模型。 另外,我有 INDEX 和 SHOW 路线。
所以在 INDEX 路线上,我有兴趣只返回已发布的 cmets 数量。我做了下一个方法:
StorySchema.methods.comments = function (cb) {
return this.model('Comment').find({ storyId: this._id, published: true }, cb);
}
这是我的 INDEX 路线(目前显示 4 个最新故事):
Story.find({}, '-content')
.sort('-dateCreated')
.limit(4)
.exec((err, found) => {
found.map(async f => f.comments = await f.comments())
if (err) return res.json({ err });
res.json(found);
})
我没有在 StorySchema 中定义 cmets 字段,但我想附上它只是为了展示,我不打算保存它。问题是,cmets 字段没有显示。即使我在 Schema 中定义它,它也不会改变。
如何将字段附加到 mongoose 文档,仅用于显示目的?
【问题讨论】:
标签: node.js mongodb express mongoose