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 extract properties from json format data?

I am trying to learn node.js in doing so I came across a problem.
Here is the code:

exports.postLogIn = (req, res, next) => {
  User.find({ name: req.body.username, emailid: req.body.emailid })
    .then((result) => {
      if (result.length) {
        console.log("value of result: " + result);
        res.render("shop", { logged: true, name: req.body.username });
      } else {
        res.render("login", { notlogged: true });
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

When I do
console.log(result)

I get output as:

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

{
  _id: new ObjectId("61bab8123a555f52d3f190e3"),
  name: 'Patrik',
  emailid: 'patrik@gmail',
  __v: 0
}

I want to extract the value of _id but when I console.log(result._id) I get result as undefined

Please guide me on how to extract the value of _id

>Solution :

If you wanted to just grab the first item you could do as Xeelley said above and just reference the result[0]._id

If there are multiple results you could do an Object.keys with a .forEach

Object.keys(result).forEach(function(key) {
    console.log(result[key]._id);
});

This loops through each nested result and then allows you to access their objects. Could be useful if need to grab more than one in the future!

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