I'm in front of a huge problem that I cannot solve. I want to get the result of the function collection.find()
of Mongodb then put the result in a variable that I could reuse in another function running independently.
Because it's a little thorough to explain, here's the code:
client.connect(function (err) {
assert.equal(null, err);
const db = client.db(myDatabase);
const collection = db.collection(myCollection);
collection.find({}).toArray(function (err, docs) {
//docs is the final result that I want to store in a variable
});
});
$(myInput).change(function() {
//using docs
})
'docs' being the result of a callback, I don't know how to retrieve it in a variable. I tried to store the whole thing in a variable, I tried global variables but nothing works, I still get undefined
each time I run my program.
So yes, I could run my function into the callback of collection.find()
client.connect(function (err) {
assert.equal(null, err);
const db = client.db(myDatabase);
const collection = db.collection(myCollection);
collection.find({}).toArray(function (err, docs) {
$(myInput).change(function(docs) {
//using docs
})
});
});
but since it's a function which I run a lot of time, it would call Mongo very often and that's not the best thing for performance especially since my database is running on another computer.