M
M
Max Yaremenko2016-11-28 12:14:29
MongoDB
Max Yaremenko, 2016-11-28 12:14:29

Not validated on Update mongodb + mongoose, what am I doing wrong...?

You need to do validation when the model data changes ... When you save, the validation goes well, but when you update it does not react at all ..
What I tried:
1. added models

var ApplianceSchema = new mongoose.Schema({
  created: Date,
  updated: Date,
  name: {
    type: String,
    required: [true, 'Appliance name is required'],
    validate: {
      validator: validateUniqueName,
      message : 'Appliance name already taken'
    },
    get: escapeProperty
  }
});
----  ВОТ ЭТОТ КУСОК
ApplianceSchema.pre('findOneAndUpdate', function(next) {
  this.options.runValidators = true;
  next();
});
---  КОНЕЦ

mongoose.model('Appliance', ApplianceSchema);

2. I added the validate true option in the controller: (code with comments .. because I already tried different options .. including with different options ... the work was the same everywhere ...
/*  Appliance.findOne({
    _id: req.params.id
  }).exec(function (err, appliance) {*/
  //  if (!err && appliance) {
      var newAppliance = Appliance.findOneAndUpdate({
        _id: appliance._id
      }, {
        $set: req.body
      }, {
        runValidators: true
       // multi: false,
        //upsert: false
      }, function (err, appliance) {
        if (err) {
          res.status(500).send(e.validationErrors(err));
        }
        res.jsonp(newAppliance);
      });
 //   }
 // });

I would be grateful if someone tells me how to dig or in what direction to dig! Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Max Yaremenko, 2016-11-30
@quality_3011

problem solved - the reason for the failure of the update is the loss of context.
In order to update the data specify : context: 'query' in the options.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question