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?