从猫鼬虚拟返回布尔

时间:2020-10-25 10:19:16

标签: node.js mongoose mean-stack

在MEAN Stack项目中,我想查找是否有喜欢的评论。 “ Comment”是主要的注释架构,“ CommentReaction”架构存储喜欢该注释的用户的详细信息。使用下面的代码,我能够获得评论的喜欢数。在我的Angular代码中,我正在检查count是否大于0,并且工作正常。

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

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

1 个答案:

答案 0 :(得分:1)

您可以定义另一个virtual,然后在count上检查members

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

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

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

最后正确填充查询:

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