node js express mongodb find all documents

To find all documents in MongoDB using Node.js with Express, you can follow these steps:

  1. Import the required modules using the require keyword:
const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;
  1. Set up the MongoDB connection in your Node.js application:
const url = 'mongodb://localhost:27017';
const dbName = 'your-database-name';
const client = new MongoClient(url, { useUnifiedTopology: true });
  1. Define a route in your Express application to handle the request for finding all documents:
app.get('/findall', async (req, res) => {
  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('your-collection-name');
    const result = await collection.find({}).toArray();
    res.send(result);
  } finally {
    await client.close();
  }
});
  1. Start the Express server to listen for incoming requests:
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

These steps demonstrate how to use Node.js with Express to connect to MongoDB and find all documents in a collection.