I'm having trouble with an async function. I'm making a query (using mongoose) to a mongodb and when I try to get the info back it yields undefined.
Here's my query to the db (nested within a function):
function kquery() {
Krakentick.findOne(
{
iname: 'btcusd',
n: { $lt: now }
},
'mk c n',
function(err, tick) {
if (err) {
return console.log(err);
} else {
return tick;
}
}
);
}
and here's my async/await function:
async function compare() {
var ktick = await kquery();
console.log(ktick);
}
compare();
These functions are both in the same file, and when I run it it gives me an 'undefined'
.
While, when I just run the query function and puts up a console.log(tick)
instead of the return tick
, I get the correct information:
{ _id: 59d1199cdbbcd32a151dcf21,
mk: 'kraken',
c: 430900,
n: 1506875804217 }
I think, I'm messing up with the callback somewhere but I'm not sure where or how. Here's the full file:
const mongo = require('mongodb');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const server = mongoose.connect('mongodb://localhost/cryptoCollection', {
useMongoClient: true
});
//Loading the mongoose schema:
const { Krakentick } = require('./kraken/model/krakenModel');
var now = Math.floor(new Date());
function kquery() {
Krakentick.findOne(
{
iname: 'btcusd',
n: { $lt: now }
},
'mk c n',
function(err, tick) {
if (err) {
return console.log(err);
} else {
return tick;
}
}
);
}
async function compare() {
var ktick = await kquery();
console.log(ktick);
}
compare();
Thanks in advance for your help!