Reputation: 11
findOne return null Always
I have "user([email protected])" data in the database but User.findOne returns null always. Please Help me. I have a node running on background but it gives me null . req.body gives the email that im passing but findOne isnot working. User.create is working fine. but search queries like find,findById,findOne is not working. SomeOne please help me.
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'A user must have a unique name'],
unique: true,
},
password: {
type: String,
required: true,
unique: true,
minlength: 8,
},
email: {
type: String,
required: [true, 'A user must have a unique name'],
unique: true,
lowercase: true,
}
const User = mongoose.model("User", userSchema);
exports.getTest=async (req,res)=>{
const {email} = req.body // returns "[email protected]"
const user = await User.findOne({email})
console.log(user) //returns null
res.json({
status:"success",
data:{
user
}
})
}
Upvotes: 1
Views: 2881
Reputation: 1
const {email} = req.body // returns "[email protected]"
const user = await User.findOne({email})
// Try writing it like this.
const userEmail = req.body // returns "[email protected]"
const user = await User.findOne({email:userEmail})
//consdering there is a email column named email in db
Upvotes: -1
Reputation: 11
Documents should save active: true
in the database. but instead, I'm saving every document as false as the default value. So, this is my answer if anyone in the future finds it useful let me know. Take care and goodbye
Upvotes: 0
Reputation: 85
I have a feeling your issue lies in the first two lines of your test?
const {email} = req.body // returns "[email protected]"
const user = await User.findOne({email})
If your req.body
just returns the email string, then maybe your query isn't in the right JSON format?
Are you sure that the query actually ends up being User.findOne({email: "[email protected]"})
instead of just User.findOne("[email protected]")
?
Also not sure if you need exec()
at the end, but it does execute the query and return a Promise...
Upvotes: 0