Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在重新加载页面时停止节点向mongodb插入数据_Node.js_Mongodb_Express - Fatal编程技术网

Node.js 如何在重新加载页面时停止节点向mongodb插入数据

Node.js 如何在重新加载页面时停止节点向mongodb插入数据,node.js,mongodb,express,Node.js,Mongodb,Express,我有一个带有表单的页面,允许您将信息插入名为“Farm”的集合中。该函数可以工作,但是如果我重新加载页面,信息会再次提交到页面中。我创建了一个过滤器函数,如果req.body具有类似的名称和种类属性,则可以避免插入数据。但是,我觉得有一个更好的方法来做这件事。下面是创建信息并将数据推送到mongodb的代码 var mongoose = require('mongoose'); var f = mongoose.model('Farm'); module.exports create

我有一个带有表单的页面,允许您将信息插入名为“Farm”的集合中。该函数可以工作,但是如果我重新加载页面,信息会再次提交到页面中。我创建了一个过滤器函数,如果req.body具有类似的名称和种类属性,则可以避免插入数据。但是,我觉得有一个更好的方法来做这件事。下面是创建信息并将数据推送到mongodb的代码

var mongoose = require('mongoose');
var f = mongoose.model('Farm');    

module.exports create = function(req,res){
      var obj = req.body;
      console.log(obj)
      f.find({}, function(err,docs){
        var same = docs.some(function(element,index){
          return (element.name === obj.name && element.species === obj.species);
        })

        if(same === true){
          console.log('That name is already in the database');
          res.render('add',{msg:"Animal is already in the database"});
        }else{
          f.create({

            name: obj.name,
            species: obj.species.toLowerCase(),
            sex:obj.sex,
            weight: obj.weight,
            age: obj.age,


          }, function(err,info){
            if (err){

              throw err;
            }

              var message = 'Congratulations you have successfully added a '+info.species;
                res.render('add',{msg:message})



          })
        }
      })

    }

通常,此问题的解决方案是在成功插入后将用户重定向到另一个页面(但如果有错误,则不会这样做,因此可以编辑并重新提交表单)

res.redirect('/success')