Node.js 从Mongoose虚拟机返回布尔值

Node.js 从Mongoose虚拟机返回布尔值,node.js,mongoose,mean-stack,Node.js,Mongoose,Mean Stack,在MEAN stack项目中,我想知道是否有喜欢的评论。“Comment”是acutal注释模式,“CommentReaction”模式存储喜欢注释的用户的详细信息。使用下面的代码,我可以得到评论的喜欢次数。在我的角度代码中,我检查计数是否大于0,以及它是否正常工作 commentSchema.virtual('likes', { ref: 'CommentReaction', localField: '_id', foreignField: 'commentId', count

在MEAN stack项目中,我想知道是否有喜欢的评论。“Comment”是acutal注释模式,“CommentReaction”模式存储喜欢注释的用户的详细信息。使用下面的代码,我可以得到评论的喜欢次数。在我的角度代码中,我检查计数是否大于0,以及它是否正常工作

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

但我希望restapi会相应地返回true或false。如何修改上述代码以仅返回true或false?

您可以定义另一个
virtual
并检查
成员的
count

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);

不存在于箭头函数中,顺便说一句,只需将
()=>{}
替换为
函数(){}
中的
.get
部分中的第一个block@Sebasti阿内斯皮诺萨:哦,你说得对。修好了,谢谢:)