Thursday 8 June 2017

MongoDB Query in Node JS returning null when using a JS var in the query

I am trying to send information back to clients based on a id they have given on a GET request from a MEAN server.

This is my code

 app.get('/contactlist/:id', function (req, res) {
  var id = req.params.id;
  console.log(id);
  db.transactions.findOne({id:{"$exists":true}}, function (err, doc) {
    res.json(doc);
  });
}); 

For Example when i enter http://127.0.0.1:3000/contactlist/332602842017

332602842017 is the id sent by the clients. This is then simply stored in a variable and used later in a mongoDB query. The console.log(id) has displayed the matched number between what was entered in the website and received by the server in my console.

The problem is the query made on the server with the prior code returns a null .

I have then tried the same query on mongodb.

db.getCollection('transactions').findOne({332602842017:{"$exists":true}})

It worked, the query returned data and was a success.

I had also tried changing my code on the server from

db.transactions.findOne({id:{"$exists":true}}, function (err, doc) {

to

db.transactions.findOne({332602842017 :{"$exists":true}}, function (err, doc) {

the results were also a success and returned datas.

What is the problem with the var id that i have declared? I have used the same method and it works when i have used for a delete and PUT request. Thank you for the time



via Michael Ek

No comments:

Post a Comment