简体   繁体   中英

confirming if an email already exists in a MongoDB database

I wrote this code to check if an email already exists in the database:

async store (req,res) {
const email = req.body.email;

let user = await User.findOne ({ email: email });

if (user) {
    console.log('Already exist.')
};
(...)
}

But it's not working: I can store the info in the User collection but it's email is not verified.

I'm using Mongoose.

What I'm doing wrong?

You need to use exec() at the end to actually run the query:

let user = await User.findOne({ email: email }).exec();

Also, since you're using await , make sure the containing function is marked async .

I am limited in the information I can give you because you just say "It's not working". That doesn't tell me anything. Do you run it and nothing happens? Does it give you an error? People on this site don't like to hear the words: "it's not working".

db.Collection.find({ /* criteria */}).limit(1).size();

You haven't described your use case, but if you're looking to avoid email collisions, using mongoose, when you define the object's schema, you can use the unique: true option. It will then reject any new or updated User that submits an already stored email.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM