仅当数据尚不存在时才将数据添加到数据库(Node 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("/");}
            });}
    });
});

但是当我使用它时,即使我输入了已经存在的数据,它仍然会将其添加到数据库中。我使用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');
            }
        });
    }
});

你为什么不尝试用你的 mongo 模式字段来做,比如,

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

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

这也将减少find数据库调用。

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

最新更新