我有一个自定义验证,当我上传图像到mongoDb。原始名称应该是唯一的。如果它通过验证,代码将正常运行。但是如果失败了,它会产生错误。它表示带有2个参数的自定义验证器)在猫鼬> = 4.9.0中被弃用。是否有另一种方法来验证原始名称的唯一性?或者一种方法来捕捉错误?请帮忙。MongoDB - 处理错误事件
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');
}
});
});
模型
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);
}
如何捕获错误? –
在使用'.validate'时检查值是否为空或者没有。 – hardy