Tuesday 11 April 2017

MongoDB - Handle error event

I have a custom validation when I upload an image to mongoDb. The original name should be unique. If it passes the validation, the code runs properly. But if it fails, it produces error. It says that custom validators that take 2 arguments) are deprecated in mongoose >= 4.9.0. Is there another way to validate the uniqueness of the originalname? Or a way to catch the error? Please help.

router.post('/upload',function(req,res){

    Item.schema.path('originalname').validate(function(value, done) {
    Item.findOne({originalname: value}, function(err, name) {
      if (err) return done(false);
      if (name) return done(false);

      done(true);
    });
  });

    upload(req,res,function(err, file) {
        if(err){
          throw err;
        }
        else{
          var path = req.file.path;
          var originalname = req.file.originalname;
          var username = req.body.username;

          var newItem = new Item({
            username: username,
            path: path,
            originalname: originalname
          });

          Item.createItem(newItem, function(err, item){
            if(err) throw err;
            console.log(item);
          });

          console.error('saved img to mongo');
          req.flash('success_msg', 'File uploaded');
          res.redirect('/users/welcome');

        }
    });
});

model

var ItemSchema = mongoose.Schema({
username: {
  type: String,
  index: true
},
 path: {
   type: String
 },
 originalname: {
   type: String
 }
});

var Item = module.exports = mongoose.model('Item',ItemSchema);

module.exports.createItem = function(newItem, callback){
  newItem.save(callback);
}



via Lawrence Ricafort Bacus

No comments:

Post a Comment