Sending order to vendor's email - API in Node & Mongodb using nodemailer
Published: 2023-07-27 07:58:04

**Step 1**: 
Create a product collection with name,price and stock.

```
// Define the schema for the product collection
const productSchema = new mongoose.Schema({
  name: { type: String, required: true },
  price: { type: Number, required: true },
  stock: { type: Number, required: true, default: 0 }, // Default stock is set to 0
});
```
**Step 2**: 
Create a vendor collection with vendor name and vendor email.

```
 
// Define the schema for the vendor collection
const vendorSchema = new mongoose.Schema({
  vendorname: { type: String, required: true },
  vendorEmail: { type: String, required: false }, // Email is not required
});

```
**Step 3**: 
Create an order collection with a vendorid, orderList containing an array of products and their quantities.

```
// Define the schema for the order collection
const orderSchema = new mongoose.Schema({
  vendorid: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Vendor' },
  orderList: [
    {
      product: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Product' },
      quantity: { type: Number, required: true, default: 1 },
    },
  ],
});
```

**Step 4**: 
Send the order to the vendor's email if the vendor email exists.

```
const express = require("express");
const mongoose = require("mongoose");
const nodemailer = require("nodemailer");
const Order = require("./order");
const transporter = nodemailer.createTransport({
  host: "smtp.example.com",
  port: 587,
  auth: {
    user: "your-email@example.com",
    pass: "your-email-password",
  },
});
app.post("/send-order", async (req, res) => {
  try {
    const { vendorId, orderList } = req.body;

    if (!vendorId || !Array.isArray(orderList) || orderList.length === 0) {
      return res.status(400).json({ message: "Invalid request parameters" });
    }

    const vendor = await Vendor.findById(vendorId);
    if (!vendor || !vendor.vendorEmail) {
      return res
        .status(404)
        .json({ message: "Vendor not found or email not provided" });
    }
    let emailContent = `
    <h1>New Order</h1>
    <table style="border-collapse: collapse; width: 100%;">
      <thead>
        <tr>
          <th style="border: 1px solid #dddddd; text-align: left; padding: 8px;">Product</th>
          <th style="border: 1px solid #dddddd; text-align: left; padding: 8px;">Quantity</th>
        </tr>
      </thead>
      <tbody>
  `;

    orderList.forEach((orderItem) => {
      emailContent += `
      <tr>
        <td style="border: 1px solid #dddddd; text-align: left; padding: 8px;">${orderItem.product.name}</td>
        <td style="border: 1px solid #dddddd; text-align: left; padding: 8px;">${orderItem.quantity}</td>
      </tr>
    `;
    });

    emailContent += `
      </tbody>
    </table>
  `;

    const mailOptions = {
      from: "your-email@example.com",
      to: vendor.vendorEmail,
      subject: "New Order",
      text: emailContent,
    };

    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        console.error("Error sending email:", error);
        res.status(500).json({ message: "Failed to send the order email" });
      } else {
        console.log("Email sent:", info.response);
        res.status(200).json({ message: "Order email sent successfully" });
      }
    });
  } catch (error) {
    console.error("Error processing the request:", error);
    res.status(500).json({ message: "Internal server error" });
  }
});

```