I want to update the variable test to the result of the database collection that I queried.
var test;
db.collection('locale').find().toArray(function(err,results){
console.log(results);
});
I want to update the variable test to the result of the database collection that I queried.
var test;
db.collection('locale').find().toArray(function(err,results){
console.log(results);
});
You can simply set the results
value from function callback to test
variable. You can then iterate results array to get the values.
var test;
db.collection('locale').find().toArray(function(err,results){
if(err)
console.log(err);
else {
console.log(results);
test = results;
for(var i = 0; i < results.length; i++) {
//process the results
}
}
});
this is not the best way to do that.. if you want to return response as json you have to add send()
or render()
inside the callback function.
you are trying to work around asynchronous feature. why?
i think you are using nodejs. right? and you want to do some synchronous query. use this Mongo Sync
var Server = require("mongo-sync").Server;
var server = new Server('127.0.0.1');
var result = server.db("testdb").getCollection("testCollection").find().toArray();
console.log(result);
You have two options:
First, you can use ES6/2015 to have a better variables scope, so you have to write your code this way:
let test;
db.collection('locale').find().toArray((err,results) => {
console.log(results);
// it Work
test = results
});
Secondly, you can create an _this variable:
var _this = this;
var test;
db.collection('locale').find().toArray(function(err,results){
console.log(results);
// it Work too
_this.test = results;
});
In my opinion, the first case with ES6 is a better way and it is more readable.