【问题标题】:How to add Virtual field after querying another Model查询另一个模型后如何添加虚拟字段
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 它会抛出这个错误,TypeError: Invalid value for schema path commentCount.type``
猜你喜欢
  • 2019-12-12
  • 2013-11-13
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多