Monday, 17 April 2017

1 user can add 1 review for one hotel/motel/object [Node.js & MongoDB]?

I am building a project in Node.js (using Express and MongoDB(with Mongoose) where logged-in users can add reviews to hotels. However I don't want a user to add more than one review to a hotel (will be able only to edit or delete the existing).

So I decided to create a middleware function which is going to check if the logged-in user ID matches any of the hotel's reviews author's ID. If true, I will redirect the user back (of course adding flash message that the user has already added a review to the hotel ... etc etc). But it is not going very tidy for me.

In the hotel's model I have implement reviews property where I am storing only the referring review's ids

middleWare.noRepeat = function(req, res, next){
  if(req.isAuthenticated()){
      Hotel.findById(req.params.id, function(err, foundHotel){
          if(err){
              console.log(err);
          } else{
             foundHotel.reviews.forEach(function(review){
                 Review.findById(review, function(err, foundReview) {

                    if(err){
                        console.log(err);
                    } else{
                        if(foundReview.author.id.equals(req.user._id)){
                            res.redirect("back");
                            //flash message to be implemented
                        } else {
                            next();
                        }
                    }
                 });
             });
          }
      });
  }  
};

This code doesn't work well for me. I am getting an error saying "Can't read author property of null". I think that this part here:

foundHotel.reviews.forEach(function(review){
                 Review.findById(review, function(err, foundReview) {

might be a problem. I am using review as the id argument of the findById method because in the hotel's model as I mentioned I have reviews property which is an array that stores the related review's ids. It looks something like this:

    reviews: [ ObjectId("53f3ada529cb20192ra35c8h"),
 ObjectId("12f3d6afdcd3cd15ktbcf8e98i"),
 ObjectId("1234abcdef56ghijk")]

Lastly I am only beginner with 2.5 months experience in this. This is my first project and I am sorry if this question looks stupid to you. Thank you in advance!



via G. Nick

No comments:

Post a Comment