Home > Back-end >  How to extract properties from json format data?
How to extract properties from json format data?

Time:12-17

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:

{
  _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

CodePudding user response:

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!

  • Related