0

Schema declaration

const mongoose = require('mongoose');

const reviewerSchema = new mongoose.Schema({
  reviewerId: { type: String, required: true },
  name: { type: String, required: true },
  email: { type: String, required: true },
  phone: String,
});

module.exports = mongoose.model('Reviewer', reviewerSchema);

Function's code:

async function addReviewer(item) {
  try {
    await reviewerModal.updateOne({ email: item.email }, item, {
      upsert: true,
    });
  } catch (err) {
    console.log(err);
  }
}
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29
  • 1
    Can you post the code where the validation check is not working and explain the problem in more detail? – lpizzinidev Jun 29 '22 at 07:18
  • so I am not getting any error even if I am not sending one of the required items and document is getting added in collection – Aman Srivastava Jun 29 '22 at 07:19
  • async function addReviewer(item) { try { await reviewerModal.updateOne({ email: item.email, }, item, { upsert: true }) } catch (err) { console.log(err); } } – Aman Srivastava Jun 29 '22 at 07:19
  • By using `updateOne` you are actually updating the fields passed in the `item` object of an existing `Reviewer`. The error would have been thrown in the case of the creation of a new `Reviewer` with one or some of the required properties missing. If you need to validate your `update` function you should use a library like `express-validator` https://www.npmjs.com/package/express-validator – lpizzinidev Jun 29 '22 at 07:24
  • so according to you in mongoose, if someone updates a field and while updating, they remove some required fields so no error will be thrown error check is done only for create ?? – Aman Srivastava Jun 29 '22 at 07:28
  • It is a upsert i.e item?update:create – Aman Srivastava Jun 29 '22 at 07:29
  • You can check the official docs https://mongoosejs.com/docs/4.x/docs/validation.html#:~:text=Update%20Validators&text=Mongoose%20also%20supports%20validation%20for,update()%20or%20findOneAndUpdate()%20. or this answer https://stackoverflow.com/a/15629463/13211263 for more info – lpizzinidev Jun 29 '22 at 07:31

0 Answers0