javascript – 在feathers.js Hook中调用MongoDB
作者:互联网
我想从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);
});
});
});
});
});
};
标签:javascript,node-js,mongodb,feathersjs 来源: https://codeday.me/bug/20190608/1199020.html