Abhilash Muttalli
Abhilash Muttalli

Reputation: 1369

Fetching data from mongo using key in server js

i am accepting username and phone from the front end and now i need to send phone to mongodb and based on that phone i need to get the details of a matching student's detail.Please help me to achieve this.

this is my server code:

server.post('/phone',urlencodedParser,function(req,res){
var resp={
  Username : req.body.username,
  phn:req.body.password
}
databaseInterface.studentDetail(resp.phn);
    res.json(resp.phn);

console.log(resp);
 res.send('username :' + req.body.username + 'passwrd:' + req.body.password);
})

this is my mongoDB code:

 function studentDetail(phn){
  User.findOne({'Father.PhoneNo':phn},function(err,studentcollection2){
    if (err) return phn(err);
    return phn(null, studentcollection2);
     }).select('-__v');

}

Upvotes: 0

Views: 27

Answers (2)

Aditya K
Aditya K

Reputation: 456

The callback that you are using has some problem.

function studentDetail(phn,callback){
  User.findOne({'Father.PhoneNo':phn},function(err,studentcollection2){
    if (err) return callback(err);
    return callback(null, studentcollection2);
     }).select('-__v');

}

for ur response,

databaseInterface.studentDetail(resp.phn,  function(err, val){
    if(err) res.send('ERROR!');
    else res.send('Response');
});

Not Tested!

Upvotes: 1

Israel Zinc
Israel Zinc

Reputation: 2769

FindOne will return a promise. You need to wait for it to be fulfilled before returning your json.

To achieve that, you need to do the following:

databaseInterface.studentDetail(resp.phn).then((data,error) => {
  res.json({response:data});
});

Your query seems wrong too.

function studentDetail(phone) {
  return [yourQuery].exec()
}

I believe that's it

Upvotes: 0

Related Questions