-1

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?

LuizC
  • 57
  • 9
  • 4
    "But it's not working" define "not working". Why do you believe it isn't working? – phuzi Nov 21 '19 at 15:45
  • We need more details. Which library (mongoose?) ? What is the data in database (that is supposed to match) and what is the `email` value that you get from the `req.body` ? – Flo Nov 21 '19 at 15:47
  • Enjoy: https://stackoverflow.com/questions/7033331/how-to-use-mongoose-findone – Flo Nov 21 '19 at 15:50
  • Thank you very much all the suggestions: I edited tha question to be more clear about it. – LuizC Nov 21 '19 at 15:56

2 Answers2

2

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".

chrispytoes
  • 1,714
  • 1
  • 20
  • 53
  • It worked, thank you very much. I edited the phrase "don't working" to be more clear and more detailed. Thanks a lot! – LuizC Nov 21 '19 at 16:44
0

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.

JDunken
  • 465
  • 2
  • 7
  • Hi @JDunken, thanks for your comment. In my User model I already done that: const mongoose = require('mongoose'); const UserSchema = new mongoose.Schema({ (...) email: { type: String, unique: true }, (...) }); module.exports = mongoose.model('User', UserSchema); – LuizC Nov 21 '19 at 16:25