在feathers.js Hook里面调用MongoDB

时间:2016-09-27 09:32:38

标签: javascript node.js mongodb feathersjs

我想从feathers.js钩子中的集合中获取信息。 如何让钩子等待,直到mongodb呼叫完成?目前它发送挂钩而不等待电话完成,我尝试了返回和promieses,但没有任何作用

// 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;
  });
  })
  })
};

4 个答案:

答案 0 :(得分:4)

理想的方法是制作hook asynchronous并返回使用钩子对象解析的Promise

// Connection URL
const url = 'mongodb://localhost:27017/db';
const connection = new Promise((resolve, reject) => {
  MongoClient.connect(url, function(err, db) {
    if(err) {
      return reject(err);
    }

    resolve(db);
  });
});

module.exports = function(hook) {
  return connection.then(db => {
      const userCollection = db.collection('question');
      return userCollection.count().then(function(N) {
        const R = Math.floor(Math.random() * N);

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

              hook.data.questionid = docs._id;

              resolve(hook);
            });
        });
      });
    });
  });
};

答案 1 :(得分:1)

解决问题的方法是使用

module.exports = function(hook, next) {
    //insert your code
    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");
        hook.data.questionid = docs[0].email;
        //after all async calls, call next
        next();
      });

}

答案 2 :(得分:0)

  

您可以使用async.waterfall()异步模块

const async=require('async');

async.waterfall([function(callback) {
  userCollection.count().then(function(N) {
    callback(null, N);
  });
}, function(err, N) {
  if (!err) {
    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;
    });
  }
}])

答案 3 :(得分:0)

Daff的解决方案对我不起作用。我收到以下错误:

info: TypeError: fn.bind is not a function

解决方案是:似乎普通的钩子可以用括号注册,但是这个钩子必须在没有括号的情况下注册。的 findEnemy

exports.before = {
  all: [
    auth.verifyToken(),
    auth.populateUser(),
    auth.restrictToAuthenticated()],
  find: [],
  get: [],
  create: [findEnemy],
  update: [],
  patch: [],
  remove: []
};

findEnemy()不起作用。也许其他人遇到了同样的问题。有人能解释一下原因吗?