【发布时间】:2018-05-05 12:07:21
【问题描述】:
我希望在访问 Image 模型时显示 commentCount 字段。代码如下:
imageSchema
.virtual('commentCount')
.get(async function () {
const image_id = this._id;
const commentCount = await Comment.count({ image_id });
return commentCount;
});
在图像的最终输出中,我得到:
{ uploaded: 2018-05-04T09:24:46.063Z,
_id: 5aec26ed56d4491ef4b3d15a,
title: 'Another snake',
description: 'Lorem ipsum dolor sit, amet consectetur adipisicing elit. Exercitationem ipsa autem culpa ea enim itaque, illo inventore obcaecati commodi minus?',
photo: '4a0831c2-f8d0-459d-ab06-794ee26c6c87.jpeg',
__v: 0,
commentCount: Promise { <pending> },
id: '5aec26ed56d4491ef4b3d15a' } ]
commentCount 是一个承诺,即使在我等待承诺之后。我该如何解决这个问题?
【问题讨论】:
-
好吧,如果你这样做
let image = await Image.findById("5aec26ed56d4491ef4b3d15a"); console.log(await image.commentCount);那么这基本上应该会给你一个想法。您似乎想要发送显示来自另一个集合的“相关”计数的响应。这是一个新奇的想法,但它确实是错误的方法。请查看 MongoDB 的$lookup运算符。底线是虚拟“吸气剂”只是一个功能。它可以“返回一个承诺”,但在对象被序列化之前你不能真正让它“解决一个承诺”。
标签: node.js mongodb express mongoose mongoose-schema