Hydish Hydish - 2 months ago 33
Javascript Question

MongoDB call inside feathers.js Hook

I want to get the info from a collection inside a feathers.js hook.
How can i make the hook wait, until the mongodb call is complete? At the moment it sends the hook without waiting for the call to finish, i tried it with returns and promieses, but nothing worked



// Connection URL
const url = 'mongodb://localhost:27017/db';

//Use connect method to connect to the server

module.exports = function(hook) {
MongoClient.connect(url, function(err, db) {
const userCollection = db.collection('question');

userCollection.count().then(function(N) {

const R = Math.floor(Math.random() * N)

const randomElement = userCollection.find().limit(1).skip(R).toArray(function(err, docs) {
console.log("Found the following records");
console.log(docs)
//update hook with data from mongodb call
hook.data.questionid = docs._id;
});
})
})
};




Answer

The ideal way is to make the hook asynchronous and return a Promise that resolved with the hook object:

// Connection URL
const url = 'mongodb://localhost:27017/db';

//Use connect method to connect to the server

module.exports = function(hook) {
  return new Promise((resolve, reject) => {
    MongoClient.connect(url, function(err, db) {
      if(err) {
        return reject(err);
      }

      const userCollection = db.collection('question');
      userCollection.count().then(function(N) {
        const R = Math.floor(Math.random() * N);

        userCollection.find().limit(1)
          .skip(R).toArray(function(err, docs) {
            if(err) {
              return reject(err);
            }

            hook.data.questionid = docs._id;

            resolve(hook);
          });
      }).catch(reject);
    });
  });
};
Comments