0

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);
});
Akshay Soam
  • 1,580
  • 3
  • 21
  • 39
Rex Adrivan
  • 993
  • 1
  • 10
  • 23

3 Answers3

0

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
        }
    }
});
Akshay Soam
  • 1,580
  • 3
  • 21
  • 39
  • it returns undefined.. – Rex Adrivan Apr 21 '17 at 09:03
  • Are you sure you are entering the collection name correctly...?? – Akshay Soam Apr 21 '17 at 09:04
  • And console.log the error also, if there's one... – Akshay Soam Apr 21 '17 at 09:05
  • it retunrs the result but what I want to do is return it as a callback or variable . So i can update the test variable which is no in the function db.collection – Rex Adrivan Apr 21 '17 at 09:05
  • Actually it is returning as callback so if you need to use your test variable, you need to do that inside the callback function only. That's because it's a part of asynchronous code. – Akshay Soam Apr 21 '17 at 09:08
  • You could have done that if the call was a synchrounous one. In that case some method like `var test = db.collection('locale').find().toArraySync();` would have helped you. But there's nothing like that. – Akshay Soam Apr 21 '17 at 09:09
0

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);
Moustafa Elkady
  • 670
  • 1
  • 7
  • 17
0

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.

Antoine Amara
  • 645
  • 7
  • 11