Friday, 12 May 2017

How to check if that data already exist in the database before save

Hey guys I have a question, how to do validations before saving the edited or posted (post or put action ) data in mongoose !?

for Example, if action already exist in the database, the user will receive a some sort of error.

var mongoose = require("mongoose"),
    Schema = mongoose.Schema;

var actionSchema = new Schema({
    action: {
          type: String,
          required: true,

            },
    }); //Exporter le model

actionSchema.pre('save', function (next) { // Middlware to verify if action already existe
   var self = this;
   Action.find({
     action: self.action
   }, function (err, actions) {
     if (!actions.length) {
         next();
      } else {
          console.log('action exists: ', self.name);
          next(new Error("Action exists!"));
      }
   });
});
module.exports = mongoose.model('Action', actionSchema);



via Anis Mokeddes

No comments:

Post a Comment