mongoose express js post

// Step 1: Import necessary modules
const express = require('express');
const mongoose = require('mongoose');

// Step 2: Create Express application
const app = express();

// Step 3: Set up middleware to parse JSON requests
app.use(express.json());

// Step 4: Connect to MongoDB using Mongoose
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });

// Step 5: Define Mongoose schema for the data model
const exampleSchema = new mongoose.Schema({
  propertyName: String,
  anotherProperty: Number
});

// Step 6: Create Mongoose model using the schema
const ExampleModel = mongoose.model('Example', exampleSchema);

// Step 7: Define a route to handle POST requests
app.post('/api/examples', async (req, res) => {
  try {
    // Step 8: Create a new instance of the Mongoose model with data from the request
    const newExample = new ExampleModel({
      propertyName: req.body.propertyName,
      anotherProperty: req.body.anotherProperty
    });

    // Step 9: Save the new instance to the MongoDB database
    const savedExample = await newExample.save();

    // Step 10: Send the saved instance as the response
    res.status(201).json(savedExample);
  } catch (error) {
    // Step 11: Handle errors and send an appropriate response
    res.status(500).json({ error: error.message });
  }
});

// Step 12: Start the Express server
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});