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!
>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