Install MongoDB into API
npm i mongodb
Import MongoClient
const {MongoClient} = require('mongodb');
Create MongoDB
Client By Passing DB Server URL
// Database URL
const dbURL = 'mongodb://127.0.0.1:27017';
// Create MongoDB Client
const mc = new MongoClient(dbURL);
Connecting to mongodb
// Connect to MongoDB
mc.connect().then(client => {
console.log('Connected to MongoDB');
}).catch(err => {
console.log('Error in connecting to MongoDB');
});
Connecting to database
& collection
// Connect to MongoDB
mc.connect().then(connectionObject => {
// Connect to Database
const usersDatabase = connectionObject.db('First');
// Connect to Collection
const usersCollection = usersDatabase.collection('Users');
// Share the Collection with the APIs
app.set('usersCollection', usersCollection);
console.log('Connected to MongoDB');
// Assign Port Number to Server
const port = 4000;
app.listen(port, () => {
console.log(`Server running on port <http://localhost>:${port}`);
});
}).catch(err => {
console.log('Error in connecting to MongoDB');
});
In API Get Collection object , Write the mongoDB
command and send the response to Client
// GET Request
userApp.get('/users', async (req, res) => {
// Get usersCollection object
const usersCollection = req.app.get('usersCollection');
// Get Users data from usersCollection of DB
let users = await usersCollection.find().toArray();
// Send the data to the client
res.send(users);
});