2

I try to recover object from a mongo DB database, in a node JS file and it doesn't work.

In a file called db.js , i have made the following code :

var MongoClient = require('mongodb').MongoClient;

module.exports = {
  FindinColADSL: function() {
    return MongoClient.connect("mongodb://localhost/sdb").then(function(db) {
      var collection = db.collection('scollection');

      return collection.find({"type" : "ADSL"}).toArray();
    }).then(function(items) {
      return items;
    });
  }
};

And, I try to use it in the file server.js :

var db = require(__dirname+'/model/db.js');

var collection = db.FindinColADSL().then(function(items) {
 return items;
}, function(err) {
  console.error('The promise was rejected', err, err.stack);
});

console.log(collection);

In the result I have "Promise { }". Why ?

I just want to obtain an object from the database in order to manipulate it in the others functions situated in the server.js file.

2 Answers2

0

Then then function called on promises returns a promise. If a value is returned within a promise, the object the promise evaluates to is another promise which resolves to the value returned. Take a look at this question for a full explanation of how it works.

If you want to verify that your code is successfully getting the items, you will have to restructure your code to account for the structure of promises.

var db = require(__dirname+'/model/db.js');

var collection = db.FindinColADSL().then(function(items) {
 console.log(items);
 return items;
}, function(err) {
  console.error('The promise was rejected', err, err.stack);
});

That should log your items after they are retrieved from the database.

Promises work this way to make working asynchronously more simple. If you put more code below your collection code, it would run at the same time as your database code. If you have other functions within your server.js file, you should be able to call them from within the body of your promises.

As a rule, remember a promise will always return a promise.

Community
  • 1
  • 1
user886
  • 1,149
  • 16
  • 16
0

The callback functions created in the then() are asynchronous, thus making the console.log command execute before the promise is even resolved. Try placing it inside the callback function instead like below:

var collection = db.FindinColADSL().then(function(items) {
  console.log(items)
  return items;
}, function(err) {
  console.error('The promise was rejected', err, err.stack);
});

Or, for the sake of another example using the logger functions themselves as the callbacks, and showing that the last console.log call will actually be called before the others.

db.findinColADSL()
  .then(console.log)
  .catch(console.error)
console.log('This function is triggered FIRST')
sshow
  • 8,820
  • 4
  • 51
  • 82