1

I'm trying to get some data back when doing a get request with ajax. Express fetches some data from a hosted mongoDB and sends it back, but I can't get it to work. I've verified that I get the desired values in req.params.number, but still ajax get back an empty array for "find" and null for "findOne". If I set a literal value in the "find" call to the db, then everything works, but if I try to use a variable the result will be empty.

(Node.js with express, index.js)

.get('/getdata/:number', (req, res) => {
  (async () => {
    try {
      const client = await MongoClient.connect(url, {useNewUrlParser: true});
      const collection = client.db('practice').collection('test');
      await collection.find({ "number": 4 }).toArray(function(err, docs) {
        res.send(docs);
      });
    } finally {
      client.close();
    }
  })().catch(err => {
    debug(err.stack);
  });
})

(javascript file)

$(document).ready(function() {
  $("#btnNo").click(function (e) {
    let data = {};
    data.number = 4;

    $.ajax({
        method: "GET",
        url: `/getdata/${data.number}`,
        success: (function( data ) {
        }),
        error: (function(){
        })
    });
  });
});

Having req.params.number where the literal 4 is gives back an empty array. I have verified that the { number } is 4, or what ever i set the number to in my Ajax calls url field.

Why is it that it works with a literal but not with a variable? I've been searching all day, but I seem to be alone in this. Everyone else just asumes that variables will work.

I'm new to Node and asynchronous code, could it be that I try to get a value back form the database, but the commands don't wait for eachother so maybee req.params.number is not what I think it is when the actual call to the database is made?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
JohanLarsson
  • 195
  • 1
  • 7
  • 1
    `req.params.number` is a "string" like all request parameters. If you are searching for data with a "numeric" value then you need to cast the string as a number `find({ "number": +req.params.number })` usually does the trick. Other approaches are shown on the linked question and answers. Also not related to "this" problem, but you need to read [How to properly reuse connection to Mongodb across NodeJs application and modules](https://stackoverflow.com/q/24621940/2313887) since you absolutely do not connect to the database "per" each request. – Neil Lunn May 25 '18 at 00:41

0 Answers0