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

How to find values of keys in a mongoose document?

I have a collection named User in MongoDB. Each User in a collection has a username and password. I get a MongoDB document as a result of a find() query. Now I want to access the key value pairs from the document in JavaScript.
How to do that? So far I have tried this:

  const doesUserNamePasswordMatch = async (req_username,req_password) => {
  const doc = await user.find({username:req_username});
  console.log(doc.username);
  console.log(doc.password);
  if (!doc) {
    return false;
  }else{
    if(doc.password == req_password) {
      return true;
    }else{
      return false;
    }
  }
}

My above code gives a value as undefined. Why? I also got to know that the document in MongoDB is a BSON obejct. Why not JSON? It would have been easy to access values then. I am just stuck and frustrated at all these complexities. Please help!

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

>Solution :

Bear in mind that find method returns an array. In order to find a single document please use findOne instead. Or just get the first element from the array returned by find:

  const [doc] = await user.find({username:req_username});

Additionally, you could use lean option in mongoose in order to transform response to a pure JS object:

  const doc = await user.findOne({username:req_username}).lean();

Documentation for reference: https://mongoosejs.com/docs/tutorials/lean.html#using-lean

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