如何在查询另一个模型后添加虚拟字段

时间:2018-05-05 02:51:22

标签: node.js mongodb express mongoose mongoose-schema

我想在访问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是一个承诺,即使在我等待Promise之后。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

请在创建架构时尝试此操作:

var imageSchema= new Schema({
        commentCount : {type: mongoose.Schema.Types.count, ref: 'Comment'},
        pid: String,
        oFile: String
});