MongoDB在feathers.js中调用Hook

我想从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; }); }) }) }; 

       

网上收集的解决方案 "MongoDB在feathers.js中调用Hook"

理想的方法是使钩子asynchronous并返回一个用钩子对象parsing的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); }); }); }); }); }); }; 

解决这个问题的方法就是使用

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

你可以使用asynchronous模块的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; }); } }]) 

达夫的解决scheme并不适合我。 我得到了以下错误:

 info: TypeError: fn.bind is not a function 

解决scheme是:似乎正常的钩子可以注册括号,但这个钩子必须注册没有括号。 findEnemy

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

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