How do I write a query for mongodb atlas to read a field form a document of a collection in mongodb atlas database and display a result in postman as javascript?
I've tried using projections and toArray()
and forEach()
methods. It displays {}
. Not sure what am doing wrong. Need to display an information.
MongoClient.connect(uri, { useNewUrlParser: true }, (error, client, db) => {
if(error) {
console.log('Error occurred while connecting to MongoDB Atlas... instance due to:\n',error);
} else {
//declare database instance
db = client.db('v');
//show database connection
console.log("Database connection established!");
console.log("Connected to `" + dbname + "!");
//retrieves balance
const cursor = db.collection('users').find({}).toArray();
console.log("user" + " " + phoneNumber + " " + " balance is:" );
//json response message
res.status(200).json({ balance: cursor });
}
});
This is the result
{
"balance": {}
}
The find() of mongodb is an asynchronous method, so you have to pass a callback function to get the data. Try the below code:
MongoClient.connect(uri, {
useNewUrlParser: true
}, (error, client) => {
if (error) {
console.log('Error occurred while connecting to MongoDB Atlas... instance due to:\n', error);
return res.status(500).json({
error: err
});
} else {
//declare database instance
const db = client.db('v');
//show database connection
console.log("Database connection established!");
console.log("Connected to `" + dbname + "!");
const collection = db.collection('users');
//retrieves balance
collection.find().toArray((err, cursor) => {
if (err) {
console.log(err);
return res.status(500).json({
error: err
});
}
console.log(cursor);
//json response message
return res.status(200).json({
balance: cursor
});
});
}
});
Hope this helps :)
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.