如何限制用户对每个项目只有一个评论和评级?

how to limit users to only one comment and rating per Item?

这是我在后端控制器中的内容: 'use strict';

 var   Comment = require('../../../models/comment');

module.exports = {
    description: 'Create a Comment',
    notes: 'Create a comment',
    tags:['comment'],

    handler: function(request, reply){
        console.log('COMMM PAY', request.payload);
        Comment.create({
            itemId: request.payload.itemId,
            text: request.payload.commentText,
            rating: request.payload.rating,
            userId: request.auth.credentials._id
        }, function(err, comment){
            reply(comment);
        });
    }
};

这是我在前端控制器中的内容:

$scope.createComment = function(comment, item, rating){
                            var body = {itemId:item.itemId,
                                commentText: comment.text,
                                rating: rating};

                        Comment.create(body).then(function(res){
                            toastr.success('Review Submitted.');
                            console.log('RESdfdas.data',res.data);
                            $scope.comments.push(res.data);
                            $scope.showCommentForm = !!!$scope.showCommentForm;
                            $scope.comment = {};
                            getComments();
                        });
                        };

如何让用户对每个项目只能给出一个评论/评分?我知道我需要一个 if/else 条件来说明是否已经有一个匹配的文档/评论对象具有匹配的 userId && itemId 然后 return 一个错误?

不确定你是否需要看我的 html / jade。

有几种方法可以解决这个问题。如果使用数据库,我会有一个 'events' table(集合),每次有人评价时,它都会记录一个标识符给他们和他们评价的内容。然后你可以禁用 rating/commenting 如果他们已经有匹配的记录。

一种不太绝对的方法是将某些内容存储在本地存储中,然后检查...但是该信息可能会被删除,从而使他们可以再次访问 rate/comment。

Mongoose/mongo 让这件事变得超级简单。您需要做的就是在您的服务器端路由中创建评论。

Comment.findOne({userId : request.auth.credentials._id}, function(err,data) {
  if (err) {
    // If err (doesn't find a comment made by that user)
    // Then create one
  } else {
    // If it hits here, it means there was already a comment from that user
    // So kick them out or whatever
  }
}

有几种方法可以做到这一点,用它来指导你的思考。