0

Actually I am using mongodb with Express js framework and check the email exists with my custom code and now I want to check the email is existed in my collection or not with the package that can easy to use with the Express js framework.

If_exists(req,res,callback) {
    var mongoose = require('mongoose');
    var Auth = mongoose.model('Auth');
    Auth.findOne({email:req.body.email}, function (err1, user1) {
      if (user1) {
        var error = "email";
        var message = "Email already exists";
        callback(error,message);
        return;
      }
      else {
        var error = "";
        var message = "";
        callback(error,message);
        return;
      }
    });
  }

1 Answer 1

1

if you want to add unique records in mongoose collection using attribute

unique : true

in your model use like this email:{type: String, unique: true},

if you add like this then when you add new email and that email is already in collection then it's give you error

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help but my question is to check existing emails for unique while inserting the new one.
Auth.count({email: email}, function (err, count){ if(count>0){ //document exists }); } }); findOne() will read + return the document if it exists On the other hand, find() just returns a cursor (or not) and only reads the data if you iterate over the cursor. So in our case, we're not iterating over the cursor, merely counting the results returned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.