You haven't returned anything from that function.
You should add return before table.find
function calcDifference(){
return table.find({"entries":1}) // select entries with "entries":1
.toArray(function(err, res_spr) { // create an array of found elements
let pop = res_spr.pop(); // delete last element of the array
let storeArraySpr = []; // new array to store property "number"
for (let i = 0; i < res_spr.length; i++) {
storeArraySpr.push(res_spr[i].number);
}
var resultSpr = Math.max(...storeArraySpr); // select highest entry
return resultSpr.toFixed(8); // meant to output the result when calling the function
});
}
console.log(calcDifference());
If toArray does not return values in that callback function. You can assign a value and return it.
Note that this approach will work if toArray and find do not return promises
function calcDifference(){
let result;
table.find({"entries":1}) // select entries with "entries":1
.toArray(function(err, res_spr) { // create an array of found elements
let pop = res_spr.pop(); // delete last element of the array
let storeArraySpr = []; // new array to store property "number"
for (let i = 0; i < res_spr.length; i++) {
storeArraySpr.push(res_spr[i].number);
}
var resultSpr = Math.max(...storeArraySpr); // select highest entry
result = resultSpr.toFixed(8); // meant to output the result when calling the function
});
return result; //return the final result from the callback function
}
console.log(calcDifference());
The 3rd approach, if find and toArray are actually promises
async function calcDifference(){
return await table.find({"entries":1}) // select entries with "entries":1
.toArray(function(err, res_spr) { // create an array of found elements
let pop = res_spr.pop(); // delete last element of the array
let storeArraySpr = []; // new array to store property "number"
for (let i = 0; i < res_spr.length; i++) {
storeArraySpr.push(res_spr[i].number);
}
var resultSpr = Math.max(...storeArraySpr); // select highest entry
return resultSpr
});
}
console.log(await calcDifference());
If toArray does not return results, you can assign variable again, but the difference is now we have async/await
async function calcDifference(){
let result;
await table.find({"entries":1}) // select entries with "entries":1
.toArray(function(err, res_spr) { // create an array of found elements
let pop = res_spr.pop(); // delete last element of the array
let storeArraySpr = []; // new array to store property "number"
for (let i = 0; i < res_spr.length; i++) {
storeArraySpr.push(res_spr[i].number);
}
var resultSpr = Math.max(...storeArraySpr); // select highest entry
result = resultSpr
});
return result
}
console.log(await calcDifference());
table.findtoreturn table.findtable?toArray()is an asynchronous function. You need to useawait.toArray()is called with a callback function, it doesn't return anything. See mongodb.github.io/node-mongodb-native/4.5/classes/…