Jul 16

MongoDB Examples – 4 : Reading from MongoDB

//Install express first

//npm install express

 

var express = require('express');
var app = express();

const MongoClient = require('mongodb').MongoClient;
let db;
MongoClient.connect('mongodb://localhost/issuetracker').then(connection => {
db = connection;
app.listen(3000, () => {
console.log('App started on port 3000');
});
}).catch(error => {
console.log('ERROR:', error);
});

 

app.get('/api/issues', (req, res) => {
db.collection('issues').find().toArray().then(issues => {
const metadata = { total_count: issues.length };
res.json({ _metadata: metadata, records: issues })
}).catch(error => {
console.log(error);
res.status(500).json({ message: `Internal Server Error: ${error}` });
});
});

Skip to toolbar