仅当数据库不存在时才将数据添加到数据库(节点js)

我试图添加新的数据到数据库,只是如果它不存在。我要求用户input名称,如果名称已经存在,他/她不能input相应的数据,并显示错误“已经存在”。 这就是我要做的 –

app.post("/new",function(req,res){ Model.find({"name":req.body.name},function(err,persons){ if(err!=null) { req.flash("error","Already Exists"); res.redirect("/new");} if(err==null) { Model.create(req.body.person,function(err,newPerson){ if(err){console.log("Error");} else{ newPerson.name=req.user.name; newPerson.id=req.user._id; newPerson.save(); res.redirect("/");} });} }); }); 

但是,当我使用这个,即使我input已经存在的数据,它仍然将其添加到数据库。 我使用快递,节点js和mongodb

 Model.findOne({"name":req.body.name},function(err,person){ if(err){ //err found res.send(err) } else if(person){ // no error and also person exists req.flash("error","Already Exists"); res.redirect("/new"); } else{ // no error and and person not found so create new one let newPerson = new Model({ name : req.body.name, otherParams : req.body.otherParams }); newPerson.save(function(err){ if(err){ res.send('could not create new person'); } else{ res.send('person created successfully'); } }); } }); 

你为什么不尝试用你的mongo模式字段呢,

 name: { // other rules unique: true }, 

在新创build时,如果已经存在,则会在callback中生成error对象。

这也将减less您的find数据库调用。

添加options-object( http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate

 Model.findOne({"name":req.body.name}, {upsert:true},function(err,persons){ if(err!=null) { req.flash("error","Already Exists"); res.redirect("/new");} });