Problem with MongoDB Schema

Problem with MongoDB Schema
0
#1

Hi guys, I have a problem with the creation of a Schema. In the database I see just an empty array, I don’t understand why. Thanks


EDIT: there is a syntax error in the image but is not present in my actual code

#2

So… we’re looking for errors in an image with errors, which doesn’t reflect your current code? If this were stackOverflow, there would be MASSIVE downvotes going on right now.

Show us some code. In order to post code, simply surround your code block with three backticks before and after:

```
const ReviewSchema = new Schema({

});
```

and that will display like this:

const ReviewSchema = new Schema({
  // the content of the schema would be here.
});
#3

Mmm Ok, my fault. I wasn’t clear but the problem is not in other lines of code. Obv the backticks are all present.

const mongoose = require('mongoose');
const passportLocalMongoose = require('passport-local-mongoose');
const Schema = mongoose.Schema;

const ReviewSchema = new Schema({
  name: String,
  category: String,
  date: {
    type: Date,
    default: Date.now
  },
  foodQualityRate: [{
    taste: String,¢
    presentation: String,
    quantity: String
  }],
  serviceRate: [{
    courteus: String,
    timing: String,
    presence: String
  }],
  atmosphere: [{
    attractive: String,
    clean: String,
    temperature: String
  }],
  cleanliness: [{
    bathroom: String,
    table: String,
    floor: String
  }],
  price: [{
    priceQuality: String,
    priceQuantity: String
  }],
  notes: String,
  author: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  }
});

ReviewSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model('Review', ReviewSchema);

Follow the code inside the DB:

{
        "_id" : ObjectId("5cc32800d87af13c73ef172a"),
        "name" : "Test Ice Cream",
        "category" : "IceCream",
        "notes" : "IT was unreal!!",
        "date" : ISODate("2019-04-26T15:47:12.838Z"),
        "foodQualityRate" : [ ],
        "serviceRate" : [ ],
        "atmosphere" : [ ],
        "cleanliness" : [ ],
        "price" : [ ],
        "__v" : 0
}

Sorry for my superficiality Sir!

#4

Why is there a cent sign after taste? edit never mind, that was the error in code you mentioned.

So, moving past there, I can see that all the other values are being set, but are you pushing the values for foodQualityRate, serviceRate, atmosphere, cleanliness and price onto the array before you save this Review?

#5

I have a form that sends data to the DB.
Sorry, I don’t know how I can push the values into an array before saving the review.
This is a part of the form.

 <div class="row">
      <div class="question">
        <h2>Quality of the food</h2>
      </div>
        <div class="rate">
          <h3>Taste:</h3>
          <select name="taste" required>
            <option value="">-</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
          </select>
        </div>
        <div class="rate">
          <h3>Presentation:</h3>
          <select name="presentation"  required>
            <option value="">-</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
          </select>
        </div>
        <div class="rate">
          <h3>Quantity:</h3>
          <select name="quantity" required>
            <option value="">-</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
          </select>
        </div>
    </div>
#6

So when you accept that post on the back end, it has no way of knowing the structure for ‘quantity’, ‘presentation’, ‘taste’ etc. You would need to manually handle that.

I don’t know what your code is for the creation of a new review, probably something like:

let review = new Review({
  name: /* however you're getting your form data */,

});

With your review created, and before it’s saved, you’ll likely have to manually cram the ratings in:

review.foodQualityRate.push({
  taste: /* the form data for the taste field */,
  presentation: /* the form data for the presentation field */,
  quantity: /* The form data for the quantity field */
});
review.serviceRate.push({
  // and do the same for each of the array-type nodes in your Review
});

review.save();

Without seeing the code, this is kind of just making it up as I go.

#7

This is my file reviews.js inside the controller folder. What do you think?thanks for your help

const Review = require('../models/review');

module.exports = {
  async getReviews(req, res, next) {
    let reviews = await Review.find({});
    res.render('reviews/index', {
      reviews
    });
  },
  // FORM
  newReviews(req, res, next) {
    res.render('reviews/new');
  },
// CREATION REVIEW 
  async createReviews(req, res, next) {
    // Use req.body to create a new review
    let review = await Review.create(req.body);
    res.redirect(`/reviews/${review.id}`);
  },
  async showReviews(req, res, next) {
    let review = await Review.findById(req.params.id);
    res.render('reviews/show', {
      review
    });
  }
}
#8

… and that’s great – but node doesn’t know how to assign your various ratings. You’ll need to manually squeeze that in by changing that just a little:

async createReviews(req, res, next){
  let review = new Review(req.body);
  review.foodQualityRate.push({
    /* all the ratings for the food quality bits need to be manually set.
  });
  /****
   * ...and do the same for:
   *   - review.serviceRate.push();
   *   - review.atmosphere.push();
   *   - review.cleanliness.push();
   *   - review.price.push();
   *
   *  Each of these are not being coaxed from the data in your form
   *   submission, so they need to be manually set. Then, you can:
   ****/
  await review.save(function (err){
    if(err) return handleError(err);
  })
}

using create is fine if the entire model can be created and saved in a single statement, but in your case, its just not possible

1 Like