2017-05-08 93 views
1

我试图向数据库添加新数据,仅当它尚不存在时。我要求用户输入名称,如果名称已存在, /她无法输入相应的数据,并显示错误“已存在”。 这是林doing-只有在数据库尚未存在的情况下向数据库添加数据(节点js)

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("/");} 

      });} 
    }); 

}); 

但是,当我用这个,虽然我已经进入目前的数据,但它仍然将它添加到数据库中。 即时通讯使用快递,节点JS和MongoDB

+0

当'Model.find'找不到文档时,会设置'err'?这听起来有点不直观。你确定这是真的吗? – mingos

+0

我认为这是对的@mingos –

回答

1
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'); 

      } 
     }); 
    } 

}); 
+0

非常感谢你,很好地工作 –

+0

很高兴帮助你,干杯队友:) –

+0

你能否也请帮忙,http://stackoverflow.com/questions/43640381/reset-password-in-node-js –

0

添加的选项对象(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");} 

}); 
+0

对不起,但它没有工作。同样的问题仍然存在 –

+0

抱歉没有检查你的回调。 您的错误为空,除非发现大行数据库错误。所以只是删除你的if(err == null) 我更新了我的答案 – schaffioverflow

+0

对不起,但它仍然将数据添加到数据库没有任何错误 –

1

你为什么不尝试将其与蒙戈架构字段仿做,

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

在新创建时,如果已经存在,它将在回调中生成error对象。

这也会减少您的find数据库调用。

+0

对不起,它没有工作。我的问题仍然存在 –

+0

@RaviHooda我不认为你能够在7分钟内检查... ... –

+0

@Harish请在你的答案中包含更多的代码,以便Ravi能够理解.. –

相关问题