What steps can be taken to restrict users to providing only one comment and rating for each item?

In the backend controller, I have the following code snippet: '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);
        });
    }
};

This is what I have in the front-end controller:

$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();
                        });
                        };

I'm looking for a way to restrict users from giving multiple comments/ratings on the same item. I believe implementing an if/else conditional that checks for existing documents with matching userId and itemId would be necessary to return an error.

If needed, I can provide the HTML/Jade code as well.

Answer №1

When tackling this issue, there are a couple of approaches you could consider. One option is to utilize a database where you would have an 'events' table that records each time a user rates something, along with their identifier and the content they rated. This way, you can prevent users from rating or commenting multiple times by checking for existing records.

Another method is to save data in local storage and perform checks on it, although this information may be easily deleted, allowing users to rate or comment again.

Answer №2

Mongoose and MongoDB have streamlined the process for accomplishing this task. By implementing code similar to the following in your server-side route for comment creation, you can easily manage user comments.

Comment.findOne({userId : request.auth.credentials._id}, function(err,data) {
  if (err) {
    // If an error occurs (no comment found for that user)
    // Create a new comment
  } else {
    // If a comment already exists for that user
    // Take appropriate action
  }
}

There are multiple approaches to handling this scenario; use this as a starting point to guide your decision-making process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

By setting `queue: false` when calling jQuery's `show()` method, you can

When looking at the code below, it is clear that even though showLoader is the first call, the loader does not appear immediately. This delay is due to the fact that heavyLifting function is blocking the UI thread. function onClick() { showLoader(); ...

Is there a way to execute this process twice without duplicating the code and manually adjusting the variables?

I'm looking to modify this code so that it can be used for multiple calendars simultaneously. For example, I want something similar to the following: Here is what I currently have: This is my JavaScript code: var Calendar = { start: function () ...

Encoding URLs for LoopBack applications

I am experiencing an issue with the filter I have: { "fields": {"goal":true,"amountPledged": true,"title": true},"where": {"title": {"like":`%${this.state.searchText}%`}} } The this.state.searchText value is bio. According to my understanding, it should ...

UI Router 10 causing $digest() loop with Angular 1.4.1 when $state.go is triggered during $stateChangeStart event

My application has a state that requires authorization. I have set up an event listener for $stateChangeStart, and if the toState.data.protected condition is met but the user is not authorized, I prevent default action using e.preventDefault() and redirect ...

Page refreshing in Angular 5 consistently redirects to the home page instead of staying on the current page

I am experiencing an issue with the navigation on my application. When I navigate to routes like getEmp-by-id or page-not-found and hit refresh, the application automatically redirects me back to app-home. However, I would like it to stay on the same pag ...

What are some ways to detect if JavaScript is enabled on the client side?

In the process of creating a web application, I have structured my code to dynamically generate JavaScript functions using PHP. However, it has come to my attention that if JavaScript is disabled on the client side, my application will not function as in ...

What is the process for inserting a document into an array that is nested within another array?

My current dilemma revolves around a document (referred to as 'root') which contains an array of other documents ('stick'), each of which in turn contain another array of documents ('leaf'). Simply put: root{ stickChain[leaves ...

Using jQuery or JavaScript, extract JSON data from Yahoo Pipes

Here is the JSON format that I receive from Yahoo pipes: {"count":3, "value":{ "title":"Freak count feed", "description":"Pipes Output", "link":"http:\/\/pipes.yahoo.com\/pipes\/pipe.info?_id=565sdf6as5d4fas ...

The Stripe payment form effortlessly updates in real-time thanks to the powerful @stripe/react-stripejs module

I am experiencing some difficulties with implementing Stripe payment in my Medusa-JS Next JS frontend. Whenever I enter card details in the checkoutForm, the entire StripePayment component keeps re-rendering every time I click on anything within the form ...

What could be causing React to not re-render the page when the button is clicked?

function MyApp() { const [usersData, setUsersData] = useState([]) useAsyncEffect(async () => { const response = await fetch('https://jsonplaceholder.typicode.com/users') const users = await response.json() setU ...

Having issues with Bootstrap flip div not functioning properly when clicked on a mobile device?

I am currently working on a website and encountering an issue. Here is the code snippet I am using: https://jsfiddle.net/3caq0L8u/ The objective is to flip a div when a button is clicked. The button responsible for flipping the div resides in both the " ...

Using ng-bind-html does not offer protection against cross-site scripting vulnerabilities

I utilized ng-bind-html to safeguard against cross site scripting vulnerabilities. I came across information about sanitization and engaged in a discussion at one forum as well as another informative discussion. However, I encountered an issue where it di ...

What is the best way to show the initial image within every div that has the class name .className?

I am looking to only show the first image in each div with the class name "className." This... <div class="className"> <p>Yo yo yo</p> <p><img src="snoop.jpg" /></p> </div> <div class="className"> Hel ...

Struggling to incorporate blocks into Jade for Express. Encountering errors like "Max Stack Size Exceeded" and issues with setHeader

I am currently using Express along with a simple express-generator server that I created. My first task was to focus on creating the view layout and extending the index page, but unfortunately, I have encountered some challenges. Throughout my process, I& ...

Reacquire Angular Range

My table is displaying all the data, and I have applied the tablesorter plugin after binding the table. However, after applying the plugin, ng-click is not working for the table. I suspect that this issue is related to the plugin's scope object not ...

Having trouble executing partial views with node.js and AngularJS?

I have been working on my AngularJS application and everything functions correctly when I browse it. However, I've encountered an issue while trying to configure Express. The main page displays fine, but when I click on the hyperlinks to load partial ...

Issues stemming from the utilization of the $timeout feature

Just starting out with AngularJS and looking for some help on resolving an issue with $timeout in Angular JS 1.8. I've been following a course on Udemy, but I think it may be a bit outdated :(. Thank you in advance for your assistance. PS: Apologies f ...

Cufon failing to load following an ajax call

At first, cufon is used to replace the text on the main page. However, when another page file is loaded, cufon does not apply its replacement to the newly loaded content. Why is that? I tried adding cufon.refresh(); as the last function in the chain. I c ...

javascript send variable as a style parameter

screen_w = window.innerWidth; screen_h = window.innerHeight; I am trying to retrieve the dimensions of the window and store them in variables. Is there a way to then use these variables in my CSS styles? For example: img { width: screen_w; height: s ...

Troubleshoot: Why is my AngularJS bootstrap.ui modal failing to

I am experiencing an issue with displaying a modal dialog using AngularJS bootstrap.ui. After calling $modal.open(...), the screen grays out, the HTML from my templateUrl is fetched from the server, but the modal does not appear. When I click on the gray a ...