I'm setting up a service in node.js which will track URL clicks on a website. I'm having trouble viewing the data in mongoDB. I can pull the document.
_id: ObjectID("5cc0fe18f7875c00bc88de4c")
url:"google.com?ref_source=test"
count:0
Then I parse that string and end up with 0
, the count, like expected. However, when I return this count and then log it, I get the undefined error
I've tried to debug the code and stumbled upon a maybe important thing.
The node.js console prints out the URL input, it then prints out undefined
which isn't logged if I don't log the result from my function, and then it prints out Retrieved From DB: 0
. If I look at my code, Retrieved From DB: 0
should be printed out before undefined. Is this a possible problem?
var MongoClient = require('mongodb').MongoClient;
var mongourl = "mongodb://localhost:27017/";
function count() {
let string = "reapnow.ml+test"
lengths = string.split("+")
console.log(lengths)
fullurl = (lengths[0] + "?ref_source=" + lengths[1])
MongoClient.connect(mongourl, function (err, db) {
var dbo = db.db("analytics")
var query = {url: fullurl}
dbo.collection("main").find(query).toArray(function (err, result) {
let res = JSON.stringify(result)
res = res.substring(res.indexOf(":") + 1)
res = res.substring(res.indexOf(":") + 1)
res = res.substring(res.indexOf(",") + 1)
res = res.substring(res.indexOf('":') + 2)
res = res.substring(0, res.indexOf('}]'))
console.log("Retrieved From DB: " + res)
//At this point, res is 0
db.close()
return (count)
})
})
}
console.log(count()) //ouputs the word undefined.
My expected output is 0, not undefined.
Edit 1: Tried using awat/async and am I doing it wrong or is that not the right thing to do?
var MongoClient = require('mongodb').MongoClient;
var mongourl = "mongodb://localhost:27017/";
async function count() {
let string = "reapnow.ml+test"
lengths = string.split("+")
console.log(lengths)
fullurl = (lengths[0] + "?ref_source=" + lengths[1])
try{
var db = await MongoClient.connect(mongourl)
var dbo = db.db("analytics")
var query = {url: fullurl}
var result = await dbo.collection("main").find(query).toArray()
let res = JSON.stringify(result)
res = res.substring(res.indexOf(":") + 1)
res = res.substring(res.indexOf(":") + 1)
res = res.substring(res.indexOf(",") + 1)
res = res.substring(res.indexOf('":') + 2)
res = res.substring(0, res.indexOf('}]'))
console.log("Retrieved From DB: " + res)
//At this point, res is 0
db.close()
return res
}
catch(error)
{
return error
}
}
console.log(await count())