I am having an issue returning results from a Express JS model. I think my problem is a lack of understanding of callbacks and JS Classes. I just can't seem to make it work.
I have the following code.
From the server.js I have this route:
app.get('/api/v1/loralocations/:id', LoraLocation.getOne);
Which calls the Controller action below
getOne(req, res) {
const lora_location = LoraLocationModel.findOne(req.params.id);
if (!lora_location) {
return res.status(404).send({'message': 'LoraLocation not found'});
}
return res.status(200).send(lora_location);
},
.
.
.
Model
var pool = require('./mysqlDb.js');
import moment from 'moment';
class LoraLocation {
/**
* class constructor
* @param {object} data
*/
constructor() {
}
findOne(id) {
var sql = ('SELECT test FROM Test WHERE id = ?');
pool.query(sql, [id], function (err, results, fields) {
if (err) return err;
console.log(results); //works
return results; //nope
});
}
The console.log returns the results, but nothing is returned to the controller. I have gone through a number of posts but can't seem to find a solution. I think maybe I need a callback in the controller also?
Would this be a fairly standard pattern for a simple API project?
Thanks