Mohan
Mohan

Reputation: 385

Why mongo query is showing undefined in node js

I'm trying to check the data with findOne when im trying with the postman getting undefined in console.log , i checked with the same query in roboMongo and its showing the data

this is the result:-

enter image description here

Here is the code:-

exports.signIn = async( req, res ) => {
    const {
      userEmailPhone,
    } = req.body;

await  User.findOne ({ email : userEmailPhone}).then((err, user)=> {
  console.log("user..", user)
 if (user){
    res.status(200).send({
      message: "sucess"
    });
  }
 })
}

the postman response:-

enter image description here

Upvotes: 2

Views: 656

Answers (2)

coder
coder

Reputation: 906

You are sending raw json data. First you should use app.use(bodyParser.json());. Only app.use(bodyParser()); is deprecated.

This should fix it assuming you have a json body-parser

exports.signIn = async( req, res ) => {
    const {email} = req.body;
    User.findOne ({ email : email}).then((err, user)=> {
     console.log("user..", user)
     if (user){
     res.status(200).send({
       message: "sucess"
     });
   }
 })
}

Upvotes: 0

Dhruv Shah
Dhruv Shah

Reputation: 1651

Since you are already using async - await, I believe there is no need of using the .then() block.

Your code should be updated to use async and await as below:

exports.signIn = async( req, res ) => {
    const { email } = req.body;

const user = await  User.findOne ({ email : userEmailPhone})
  console.log("user..", user)
 if (user){
    res.status(200).send({
      message: "sucess"
    });
  }
}

If you still want to use the .then() block, I would recommend making the following changes in the code:

exports.signIn = async ( req, res ) => {
    const {email} = req.body;
    User.findOne ({ email : email}).then((user, err)=> {
     console.log("user..", user)
     if (user){
     res.status(200).send({
       message: "sucess"
     });
   }
 })
}

Since the promise callback for MongoDb queries has the following callback format:

.then( (res, err)  => {
     // do stuff
})

Reference : https://docs.mongodb.com/drivers/node/fundamentals/promises/

Upvotes: 1

Related Questions