I have a function in a file that I'm using to get users, the console.log() in the function works, but when using it from another file it returns undefined.
const db = client.db('TestDatabase');
const collection = db.collection('users');
exports.getUser = function(_id) {
collection.findOne({
_id: _id
}, (err, data) => {
if (err) {
console.log(err);
return;
}
//console.log(data); // Logs the proper data.
return data; // Return data?
});
}
File im using it from:
const database = require('./db.js');
let user = database.getUser(_id);
console.log(user); // This logs "undefined"
尝试给出集合名称;
db.getCollection("<COLLECTION_NAME").find({})....
I'm suspicious of the use of a callback and await
. There's no need for the callback function in getUser()
if you're going to change how you handle the response later.
In the case that you're trying to use, I would recommend getting rid of the callback and simply wrapping your calls to getUser()
in a try/catch so you don't lose your error handling, like so:
function findOne(query) { return Promise.resolve(query) } function getUser(_id) { return findOne({ _id }) } async function main() { try { let user = await getUser( 'myId' ) console.log(user) } catch (error) { console.error(error) } } main()
The other option is to pass a callback into your getUser()
function, and pass that along in your call to findOne()
instead of defining it there.
You need to make getUser return a promise if you want to call it using await
. Returning a value from your callback function doesn't return anything to the caller.
These days, findOne
returns a promise when you don't pass a callback. So you can simply do something like this.
exports.getUser = function(_id) {
return collection.findOne({
_id
});
}
The OP tries to use the function as async, but it must be qualified that way and must return a promise...
exports.getUser = async function(_id) {
return new Promise((resolve, reject) => {
collection.findOne({_id: _id}, (err, data) => {
err ? reject(err) : resolve(data)
})
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.