我想从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;
});
})
})
};
解决方法:
理想的方法是制作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);
});
});
});
});
});
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。