0

I have this document in my MongoDB

{
    _id: 603e59811a640a0d1097bc35,
    firstName: 'ABC',
    lastName: 'XYZ',
    address: 'Mars',
    age: 20,
    mobile: 9922334455,
    email: 'abc@gmail.com',
    password: 'pass',
    type: 'citizen',
    __v: 0
}

And below is the code I am using to fetch it:

router.post('/login', (req, res) => {
    const user = new User({
        userName: req.body.userName,
        password: req.body.password,
    })

    User.findOne(
        {
            email: user.userName,
            password: user.password,
        },
        (err, data) => {
            console.log(data)
        }
    )
})

In console I am getting output as:

{
  _id: 603e59811a640a0d1097bc35,
  firstName: 'ABC',
  lastName: 'XYZ',
  address: 'Mars',
  age: 20,
  mobile: 9922334455,
  email: 'abc@gmail.com',
  password: 'pass',
  type: 'citizen',
  __v: 0
}

Now, when I am trying to access the data like console.log(data.firstName) its showing me as undefined. But if I do console.log(data._id) which is the first propertie's key, its giving the correct value which is 603e59811a640a0d1097bc35

Update

I tried debugging and found this: enter image description here

The datatype of result is model. And if I use ${result._doc.firstName} its giving me the first name. But is this the correct way of accessing the properties?

Bunny Fox
  • 23
  • 1
  • 1
  • 4

2 Answers2

0

Perhaps you should use the .then() and .catch() methods on the collections, since they return a promise.

An example in your case would be:

await User.findOne({
        email: user.userName,
        password: user.password
    })
    .then(result => {
        if (result) {
            console.log(`Successfully found document: ${result}.`);
        } else {
            console.log("No document matches the provided query.");
        }
        return result;
    })
    .catch(err => console.error(`Failed to find document: ${err}`));

You can use the second parameter in .findOne() to specify any fields to include or exclude: .findOne(data, {_id: 1, username: 1, password: 0)

More information about this method: https://docs.mongodb.com/realm/mongodb/actions/collection.findOne/

tysab
  • 31
  • 1
0

OK. Solved. I used .toObject() on response data which converts model or document object into plane JS object

User.findOne({}, (err, data) => {
        const obj = data.toObject()
        console.log(objectt.firstName) // Logs 'ABC'
    })

Source of solution: How do you turn a Mongoose document into a plain object?

Bunny Fox
  • 23
  • 1
  • 1
  • 4