Express is returning undefined
in the console log. I wanted to get the data shown below.
app.get('/api/leaders/', async (req, res) => {
try {
const client = await MongoClient.connect('mongodb://localhost:27017', {useNewUrlParser: true, useUnifiedTopology: true});
const db = client.db('leaders');
const leadersList = await db.collection('leaders').find({}).toArray(function (err, result) {
console.log("Connected correctly to server");
console.log(result);
});
res.status(200).json(leadersList);
client.close();
} catch (error) {
res.status(500).json({message: 'Error connecting to db', error});
}
})
Here is the data I want returned from the db:
db.leaders.find({})
{ "_id" : ObjectId("5eb8922d17d98c2bb6f98a5a"), "username" : "kk", "score" : 20 }
{ "_id" : ObjectId("5eb8922d17d98c2bb6f98a5b"), "username" : "mj", "score" : 18 }
{ "_id" : ObjectId("5eb8922d17d98c2bb6f98a5c"), "username" : "vr", "score" : 15 }
{ "_id" : ObjectId("5eb8922d17d98c2bb6f98a5d"), "username" : "mdb", "score" : "25" }
You're trying to mix.Js callbacks
with async-await
's which is causing the issue. Try below code:
app.get('/api/leaders/', async (req, res) => {
let client;
try {
client = await MongoClient.connect('mongodb://localhost:27017', {useNewUrlParser: true, useUnifiedTopology: true});
const db = client.db('leaders');
console.log("Connected correctly to server");
const leadersList = await db.collection('leaders').find({}).toArray();
console.log('leadersList ::',leadersList);
/** I would not recommend to open & close DB connections for each API call. Find a better way to manage DB connections */
client.close();
res.status(200).json(leadersList);
} catch (error) {
if(client){ console.log('Error at DB find operation'); client.close(); res.status(500).json({message: 'Error at DB find operation', error}); }
res.status(500).json({message: 'Error connecting to db', error});
}
})
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.