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

Use a swipe gesture to move through the slideshow on a touchscreen device

I am currently working on a slideshow that allows users to navigate through images by clicking either the next or previous buttons. When a user clicks on one of these buttons, the next or previous image is loaded into the img src, as shown below. In addit ...

Troubleshooting Protractor in Intellij: A step-by-step guide

While using OSX, I successfully configured an Intellij 15 run/debug task as explained in this post below: How to debug angular protractor tests in WebStorm Although the task runs fine, unfortunately, the debug feature does not work and throws the followi ...

Using AngularJS with the Chosen Plugin to pre-select a value in a dropdown menu

After following the guidance from this URL, I successfully incorporated the chosen plugin into Angular.js. Now that I can retrieve the value, my next objective is to have the selected value be pre-selected in the chosen dropdown menu. If anyone has a sim ...

Using AngularJS forEach to assign properties to objects within a found set in ng-repeat

I am using an ng-repeat to display items from a JSON file, and they can be filtered based on user input. <tr ng-repeat="i in filteredItems = (iso3166 | filter: {alpha_2: isoQuery})"> Everything is working as expected. Each item in the "iso3166" gro ...

Switch up the picture when you press on it

I have a task involving a table where I want to switch out an image in the <td> when it is clicked, using a URL that I specify beforehand. The URL of the image will be provided when clicking on a link within the page. For example: index.html?type=d ...

JavaScript Filtering Technique

Attempting to compose an array of names for a search output page The json arrangement looks like this: data = { "artists": [ { "artistName": "a" }, { "artistName": "b" }, { "artistName": "c" }, { "artistName": "d" }, { "artistName" ...

Transfer attributes, but have exclusions in React

At times, we all have a common practice of wrapping DOM elements in custom components. <CustomComponet id="abc" title="abc" nonDomProp="abc" ...andsoforth /> In this example, the custom component wraps a button with pr ...

What is causing my basic angularjs to not function properly?

In my angularjs test instance, I am using a global variable but the alert tag is not functioning as expected. This code snippet is from my first example on codeschool. Any thoughts on why the alert is not running? <!DOCTYPE html> <html xmlns="ht ...

UI Router seamlessly loading all views

My UI router is functioning as intended, but I've noticed that when it loads a new view, it briefly displays all other views in that state before quickly removing them. What could be causing this behavior? EDIT: Upon further inspection, there is inde ...

I am attempting to link my Firebase real-time database with Cloud Firestore, but I am encountering import errors in the process

I am currently working on enhancing the online functionality of my chat app by implementing a presence system using Firebase Realtime Database. Here is the code snippet that I have created for this purpose: db refers to Firestore and dbt refers to the Rea ...

Add a .handlebars or .hbs file to an HTML document

When visiting the emberjs.com homepage, you will find an example of a todo list using Ember.js and Handlebars.js. Within the todo list, there is an extension for a .hbs file. I am curious - what exactly is a .hbs file? And how can I include a .hbs script ...

Is it possible to read an XML response as a stream using Ext JS?

Requesting an XML response can sometimes result in a slow completion time due to certain constraints. Despite this, the data begins returning quickly. I am wondering if it is feasible to read the response stream in Ext JS before it is fully complete. My u ...

Issue with date range filter functionality not functioning as expected

Struggling to get the date range filter to function properly. Selecting a date triggers it, but nothing is being added to the var filter. I've spent hours trying to solve this issue with no progress. html <div class="form-group"> <input ...

Keep an eye on the syncing progress of pouchdb replication

What is the best way to alert the user if there is a loss of Internet connection or if the server goes offline, causing live sync to stop? var localdb = new PouchDB('localdb'); var remotedb = new PouchDB('http://localhost:5984/xyz&a ...

Enhance the functionality of the directive form by incorporating additional methods

My Angular custom form needs enhancement: <form rp-form> <input type="text" value="one"> <input type="text" value="two"> <button type="submit">submit</button> </form> I am looking to incorporate a method using th ...

Chrome has a malfunction with the SVG 'use' tag

Within the SAP platform, I have a navigation system built with AngularJS and Angular Route that utilizes icon-based navigation through svg-sprite. Here is an example of my inline code: <div style="height: 0; width: 0; position: absolute; visibility: hi ...

Use jQuery to swap out two div classes within a table cell (TD) if they are

Although I'm making progress, I must confess that jQuery and CSS are not my strong suits. The objective: To create a dynamic div within a table data cell for a calendar feature. The content of the div varies based on the date range input. A filled d ...

Converting a jQuery function into AngularJS: A step-by-step guide

I'm completely new to AngularJs and I recently created a slider function using jQuery. Now, my goal is to convert this function into Angular. Below is the code snippet that I have: <div class="slide-container"> <div class="slide-s ...

`Inconsistent form variable behavior persists despite multiple ajax requests`

I'm in the process of creating a basic email submission form and I've decided to use ajax for it. The issue I'm encountering is that after successfully submitting the form once, any subsequent modifications made to the text within the form a ...

react componentdidupdate triggers never-ending iteration

When I trigger an API call to elasticsearch using onChange, it prompts a list for autocomplete. To make sure that my store is updated before rerendering, I included componentDidMount so that I am not lagging behind by one tick. Here is the code snippet: c ...