4

我想从一个 feathers.js 钩子中的集合中获取信息。我怎样才能让钩子等待,直到 mongodb 调用完成?目前它发送钩子而不等待调用完成,我尝试了返回和承诺,但没有任何效果

// 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

4 回答 4

4

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';
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);
            });
        });
      });
    });
  });
};
于 2016-09-27T15:51:21.350 回答
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();
      });

}
于 2016-09-27T12:44:45.663 回答
0

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

info: TypeError: fn.bind is not a function

解决方案是:看起来普通的钩子可以用括号注册,但是这个钩子必须不用括号注册。寻找敌人

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

findEnemy()不起作用。也许其他人遇到同样的问题。有人可以解释为什么吗?

于 2017-02-02T14:09:33.490 回答
0

您可以使用async 模块的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;
    });
  }
}])
于 2016-09-27T09:46:32.060 回答