0

Thats how I add a user object to my mongoDB. How to check if there is already another user with the same email address? I could fetch all users and look it up, but I want to have a better performance solution for that.

/* POST to Add User Service */
router.post('/adduser', function(req, res) {

// Set our internal DB variable
var db = req.db;

// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;

// Set our collection
var collection = db.get('usercollection');

// Submit to the DB
collection.insert({
    "username" : userName,
    "email" : userEmail
}, function (err, doc) {
    if (err) {
        // If it failed, return error
        res.send("There was a problem adding the information to the database.");
    }
    else {
        // If it worked, set the header so the address bar doesn't still say /adduser
        res.location("userlist");
        // And forward to success page
        res.redirect("userlist");
    }
});
});
Stennie
  • 63,885
  • 14
  • 149
  • 175
Robin Wieruch
  • 14,900
  • 10
  • 82
  • 107

3 Answers3

0

I donโ€™t know if this is very performant, but the simplest way is probably to use Mongoose for access to MongoDB. It makes you define a schema where some fields can be marked as unique, and automatically validates when saving.

Nelo Mitranim
  • 823
  • 1
  • 13
  • 13
0

I suggest you use _id (which is indexed and unique by default) instead of email to store the email address, it will even work in a shared environment. If you can't do that, then you can add a unique index. http://docs.mongodb.org/manual/tutorial/create-a-unique-index/

The downside here is that you won't be able to use a unique index in case the collection is sharded: http://docs.mongodb.org/manual/tutorial/enforce-unique-keys-for-sharded-collections/

Nikita ์›ƒ
  • 2,042
  • 20
  • 45
0
app.get('/:username',function(req , res){
db.collection.find({username:req.params.username},function(err,docs)   {if(req.params.username==docs[0].username) 
{res.send({data:"username available"} );} else{res.send({data:"username not available"})}})
 } ); 

First the req.params.username finds any document matches if exits it passes to docs and it uses if statement for validating and sends it to the browser.

bibin david
  • 1,905
  • 3
  • 12
  • 8