0

I want to get a user from MongoDB. so I should use the async function to get the right result. but it return me [object , promise]. how can I use this data?

async function getUsers() {
    var allUsers = null;
    await MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db('mydb');
        dbo.collection("users").find({})
            .toArray(function(err, results) {
                if (err)
                    throw error;
                db.close();
                allUsers = results;
            });
    });
}


app.get('/user/', function(req, res) {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db('mydb');
        var id = req.params.id;
                    var allUsers = getUsers();
             res.render('pages/user', {users: allUsers });
            db.close();
        });
});
3
  • Use await or .then and mark your function as async. Commented Jul 3, 2020 at 21:12
  • where use them? I used them. Commented Jul 3, 2020 at 21:13
  • See my answer for where to use it Commented Jul 3, 2020 at 21:17

1 Answer 1

2

You are mixing up promises and plain callbacks. You need to pick one or the other and consistently use it. Here's how to code it with promises - using the promises that MongoDb can return if used in the right way:

async function getUsers() {
    const db = await MongoClient.connect(url);
    try {
        const dbo = db.db('mydb');
        const results = await dbo.collection("users").find({});
        return results;
    } finally {
        db.close();
    }
}


app.get('/user/', function(req, res) {
    getUsers().then(allUsers => {
        res.render('pages/user', {users: allUsers });
    }).catch(err => {
        console.log(err);
        // send some sort of error response here
        res.sendStatus(500);
    });
});

I removed the database operations from inside your route handler because they weren't actually doing anything and the db stuff was already inside of getUsers().

Sign up to request clarification or add additional context in comments.

2 Comments

where can i learn more about this promises and callbacks?
@Saeedeh - I don't have a specific tutorial recommendation. There are tons of articles on Javascript promises on the web. You can start here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.