我正在尝试将新数据添加到数据库中,只有当它还不存在时。我要求用户输入名称,如果名称已经存在,他/她将无法输入相应的数据,并且会出现错误显示说它“已经存在”。 这就是我在做的-
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("/");}
});}
});
});
但是当我使用它时,即使我输入了已经存在的数据,它仍然会将它添加到数据库中。 我正在使用 express、node 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');
}
});
}
});
关于javascript - 仅在数据不存在时将数据添加到数据库(Node js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43844159/