deeveeABC deeveeABC - 3 months ago 12
Node.js Question

Do not allow two names to be the same - mongodb

I have a REST API, that allows a user to add a name and url. On this POST request, the name and url are added into my mongodb.

This is the POST request

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


And this is how it is added to the dbs:

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


This is my route which allows POST:

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


This way I am allowed to add multiple urls with the same name and url - there is no validation.

How can I make sure that an error is thrown when a user tries to insert the same name and/or url into the dbs again?

I am not sure where to start, but I assume this is a dbs option? E.g. findById if it exists, otheriwse add to the dbs?

Tom Tom
Answer

Mongoose has validation some options specified in their documentation.

In your model, where you define your schema. Use an object to validate the input.

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

See: http://mongoosejs.com/docs/validation.html

However, its not ideal to use this on its own. It will just throw an error and not give the user any feedback. To do this, we could check to see if a record exists in the database.

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)
            })
        }

    });
})
Comments