【问题标题】:Return Bool from Mongoose virtual从 Mongoose 虚拟返回 Bool
【发布时间】:2021-02-07 20:27:12
【问题描述】:

在 MEAN 堆栈项目中,我想查找是否有评论的点赞。 “评论”是实际评论模式,“评论反应”模式存储喜欢评论的用户的详细信息。使用下面的代码,我可以获得评论的点赞数。在我的 Angular 代码中,我正在检查 count 是否大于 0 并且它工作良好。

commentSchema.virtual('likes', {
  ref: 'CommentReaction',
  localField: '_id',
  foreignField: 'commentId',
  count: true
});

但我希望 REST API 相应地返回 true 或 false。如何修改上面的代码以仅返回 true 或 false?

【问题讨论】:

    标签: node.js mongoose mean-stack


    【解决方案1】:

    您可以定义另一个virtual 并在count 那里检查members

    commentSchema.virtual('hasLikes', {
        foreignField: 'likes', // must match the previous virtual
    }).get(function () {
        return this.likes > 0;
    });
    

    确保为toJSON/toObject 启用virtual 选项:

    commentSchema.set('toObject', { virtuals: true });
    commentSchema.set('toJSON', { virtuals: true });
    

    最后正确填充查询:

    const res = await Comment.find({}).populate('likes').populate('hasLikes').exec();
    console.log(res);
    

    【讨论】:

    • this 在箭头函数中不存在顺便说一句,只需在第一块的.get 部分将() => {} 替换为function() {}
    • @SebastiánEspinosa:哦,你是对的。修复了,谢谢:)
    猜你喜欢
    • 2019-06-17
    • 1970-01-01
    • 2014-07-19
    • 2018-01-24
    • 1970-01-01
    • 2023-02-10
    • 2010-10-31
    • 1970-01-01
    • 2019-06-28
    相关资源
    最近更新 更多