node api with mongodb

// Step 1: Install necessary dependencies using npm
// Run this command in your terminal to install required packages:
// npm install express mongoose body-parser

// Step 2: Set up Express and required modules
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();
const PORT = 3000;

// Step 3: Connect to MongoDB database using Mongoose
mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
const db = mongoose.connection;

db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', function () {
  console.log('Connected to MongoDB database');
});

// Step 4: Define a Mongoose schema for your data
const Schema = mongoose.Schema;
const exampleSchema = new Schema({
  name: String,
  age: Number,
  email: String,
});

// Step 5: Create a Mongoose model based on the schema
const ExampleModel = mongoose.model('Example', exampleSchema);

// Step 6: Set up middleware to parse incoming requests
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Step 7: Create API endpoints using Express routes
// Example GET endpoint to retrieve all data
app.get('/api/examples', async (req, res) => {
  try {
    const examples = await ExampleModel.find();
    res.json(examples);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Example POST endpoint to add new data
app.post('/api/examples', async (req, res) => {
  const example = new ExampleModel({
    name: req.body.name,
    age: req.body.age,
    email: req.body.email,
  });

  try {
    const newExample = await example.save();
    res.status(201).json(newExample);
  } catch (err) {
    res.status(400).json({ message: err.message });
  }
});

// Step 8: Start the server to listen on specified port
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});