X
X
xxx1233212018-08-31 00:40:02
MongoDB
xxx123321, 2018-08-31 00:40:02

How to send data from mongodb?

I am using mongodb driver.
There is a base 'qq' and a collection 'bb' .

router.get('/1',(ctx) => {
    mongoClient.connect(url, function(err, client){
        client.db("qq").collection("bb").find({}).toArray((err, users)=>{
            ctx.body = users
            console.log(users)
            client.close()
        })
    })
})

With such a request, what I expect is displayed in the console, but it ctx.body = users
doesn’t show anything,
what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2018-08-31
@xxx123321

as far as I understand koa?
in order for koa to wait for your asynchronous action in the route, you need to return a promise:

router.get('/1', ctx => new Promise(resolve => {
    mongoClient.connect(url, (err, client) => {
        client.db("qq").collection("bb").find({}).toArray((err, users) => {
            ctx.body = users;
            console.log(users);
            client.close();
            resolve();
        });
    });
}));

PS Opening a new database connection for every request is not very good...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question