MERN

⌘K
  1. Home
  2. Docs
  3. MERN
  4. server configuration

server configuration

server.js

const express = require("express");
const app = express();

app.listen(5000,()=>{
    console.log("Server Started ");

});

database.js

const mongoose = require('mongoose');

async function connectToMongoDB() {
  try {
    // Define your MongoDB connection URL
    const dbURL = 'mongodb://localhost:27017/ecommerce-db';

    await mongoose.connect(dbURL, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });

    console.log('Connected to MongoDB');
  } catch (error) {
    console.error('MongoDB connection error:', error);
  }
}

connectToMongoDB();

// Export the MongoDB connection
module.exports = mongoose;

models/products.js

const mongoose = require('./database'); // Import the MongoDB connection

// Define the Product Schema
const productSchema = new mongoose.Schema({
  name: { type: String, required: true },
  description: { type: String, required: true },
  price: { type: Number, required: true },
  // Add more fields as needed
});

// Create a Product model from the schema
const Product = mongoose.model('Product', productSchema);

// Export the Product model
module.exports = { Product };

routes/product.js

const express = require('express');
const router = express.Router();
const { Product } = require("../models/products") // Import the Product model

// Create a new product
router.post('/products', async (req, res) => {
  try {
    const product = new Product(req.body);
    await product.save();
    res.status(201).json(product);
  } catch (error) {
    res.status(500).json({ error: 'Error creating product' });
  }
});

// Fetch all products
router.get('/products', async (req, res) => {
  try {
    const products = await Product.find();
    res.json(products);
  } catch (error) {
    res.status(500).json({ error: 'Error fetching products' });
  }
});

module.exports = router;

server.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = process.env.PORT || 5000;

// Import the database connection and API routes
const mongoose = require('./database'); // Import the MongoDB connection
const productRoute = require('./routes/products'); // Import your API routes

// Middleware
app.use(bodyParser.json());
app.use(cors());

// Use the API routes
app.use('/', productRoute);

// Start the server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

check route

How can we help?