2017-04-11 72 views
0

我有一个自定义验证,当我上传图像到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); 
} 

回答

0

可以提供惟一喜欢的那场: -

var ItemSchema = mongoose.Schema({ 
username: { 
    type: String, 
    index: true 
}, 
path: { 
    type: String 
}, 
originalname: { 
    type: String, 
    unique:true // this string will be unique all over the database 
} 
}); 

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

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

如何捕获错误? –

+0

在使用'.validate'时检查值是否为空或者没有。 – hardy

0

要保存到数据库之前验证的独特性,你可以尝试findOne旅游名:

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

Item.findOne({originalname: req.file.originalname}, function(err, name) { 
     if (err) return done(false); // errors 
     if (name) return done(false); // check for existence of item here 

     done(true); 
    }); 
}); 

如果findOne函数没有响应任何数据,这意味着,集合中没有相同原始名称的文档,并且您可以继续将文档添加到集合

+0

我已经修改过。不管怎么说,还是要谢谢你。 :) –

+0

没问题,现在你可以检查名称,如果没有数据匹配这个原始名称,并且如果没有数据 - 继续添加到数据库。另一种方法是设置文件名随机,以避免重复的文件名 –

+0

好:)如何在同一时间查询两个字段?像Item.findOne({'two fields here'})。它们应该是TRU或FALSE。就像在PHP中。 –