Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongodb FindOne returns object with undefined property

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

screenshot

My postman post request :

screenshot postman

>Solution :

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

Like this

And you should create async function and use await for get data then log that

const user = await Userdb.findOne({name: name});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading