2016-08-25 77 views
0

我有一个REST API,允许用户添加名称和URL。在这个POST请求中,名称和URL被添加到我的MongoDB中。不允许两个名称相同 - mongodb

这是POST请求

curl -XPOST http://localhost:8080/urls -d 'name=John&url=http://111.11.1.111:1111' 

,这是它是如何加入到DBS:

{ "_id" : ObjectId("57bd87e7c94363a17620ab4c"), "name" : "John", "url" : "http://111.11.1.111:1111", "__v" : 0 } 

这是我的路线,它允许POST:

router.post('/', function (req, res, next) { 
    Urls.create(req.body, function (err, post) { 
    if (err) return next(err) 
    res.json(post) 
    }) 
}) 

这我可以使用相同的名称和网址添加多个网址 - 没有任何验证。

如何确保在用户尝试再次向dbs中插入相同的名称和/或url时发生错误?

我不确定从哪里开始,但我认为这是一个dbs选项?例如。 findById是否存在,其他情况下添加到dbs中?

+0

您可以创建索引,请参考以下链接[它包含了你的问题的解决方案(http://stackoverflow.com/questions/12395118/mongodb-setting-unique-field) –

回答

0

Mongoose验证了他们的文档中指定的一些选项。

在您的模型中,您定义模式的位置。使用一个对象来验证输入。

name : { type : String , unique : true, required : true }, 
url: { type : String , unique : true, required : true } 

参见:http://mongoosejs.com/docs/validation.html

但是,它不是理想的使用上一把。它只会抛出一个错误,而不会给用户任何反馈。为此,我们可以检查数据库中是否存在记录。

router.post('/', function (req, res, next) { 

    //Query the database for that name 
    Urls.findOne({'name': req.body.name}, function (err, name) { 
     //If a result is returned, throw an error 
     if (name) { 
      res.send({available: false}); 
     } 
     //If not result - its unique and we can continue. 
     if (!name) { 
      Urls.create(req.body, function (err, post) { 
       if (err) return next(err) 
       res.json(post) 
      }) 
     } 

    }); 
}) 
相关问题