I'm trying to get a user from my collection with findOne using its name attribute but it returns undefined whereas my user is in the db.
This is my schema :
var schema = new mongoose.Schema({
name: {
type: String,
required: [true, "Please enter a name"],
maxlength: 32,
},
password: {
type: String,
required: true,
minlength: [6, "Password must be at least 6 characters"],
},
email: {
type: String,
required: true,
unique: true,
},
isAdmin: {
type: Boolean,
default: false,
},
});
const Userdb = mongoose.model("userdb", schema);
module.exports = Userdb;
And this is where i try to get my user :
const name = req.body.name;
const password = req.body.password;
const user = Userdb.findOne({name: name});
// console.log(user.name, user.password);
if (user.name === undefined)
return res.status(400).send({ message: "User not found" });
const dbpassword = user.password;
where my console.log returns undefined
In the db :
My postman post request :
CodePudding user response:
Check your body request and sure you has data in db collection with this condition. If data of collection has not match query mongoose return you undifined.
- Send request in raw mode and set Json type to send request
And you should create async function and use await for get data then log that
const user = await Userdb.findOne({name: name});