Write an API to place order in express and mongodb.
Tags: javascript, node, backend
Published: 2023-08-18 07:57:02

1. Define a customer schema collection.

```
// Define the customer schema
const customerSchema = new mongoose.Schema({
  customerMobileNumber: {
    type: String,
    required: true
  },
  orders: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Order'
  }]
});

// Define the customer model
const Customer = mongoose.model('Customer', customerSchema);

module.exports = Customer;
```

2. Define an "Order" schema collection

```
const mongoose = require('mongoose');

// Define the order schema
const orderSchema = new mongoose.Schema({
  customerMobileNumber: {
    type: String,
    required: true
  },
  itemId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Item',
    required: true
  },
  itemName: {
    type: String,
    required: true
  },
  categoryId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Category',
    required: true
  },
  taxId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Tax',
    required: true
  },
  orderDate: {
    type: Date,
    default: Date.now
  },
  subTotal: {
    type: Number,
    required: true
  },
  total: {
    type: Number,
    required: true
  }
});

// Define the order model
const Order = mongoose.model('Order', orderSchema);

module.exports = Order;
```
3. Create an API  to place a new order. The API will check if the customer exists based on their mobile number. If the customer doesn't exist, a new customer will be created. If the customer already exists, a new order will be added to their orders array.

```

const Customer = require('./models/customer'); 
const Order = require('./models/order'); 

// Place a new order
app.post('/place-order', async (req, res) => {
  const { customerMobileNumber, itemId, itemName, categoryId, taxId, subTotal, total } = req.body;

  try {
    let customer = await Customer.findOne({ customerMobileNumber });

    if (!customer) {
      customer = new Customer({ customerMobileNumber });
    }

    const order = new Order({
      customerMobileNumber,
      itemId,
      itemName,
      categoryId,
      taxId,
      subTotal,
      total
    });

    customer.orders.push(order);

    await customer.save();
    await order.save();

    res.status(201).json({ message: 'Order placed successfully', order });
  } catch (error) {
    console.error('Error placing order:', error);
    res.status(500).json({ message: 'An error occurred while placing the order' });
  }
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
```
4. Create an API to retrieve orders from the customer collection based on a customer's mobile number.

```
const Customer = require('./models/customer'); 
// Retrieve orders based on customer mobile number
app.get('/orders/:customerMobileNumber', async (req, res) => {
  const customerMobileNumber = req.params.customerMobileNumber;

  try {
    const customer = await Customer.findOne({ customerMobileNumber }).populate('orders');

    if (!customer) {
      return res.status(404).json({ message: 'Customer not found' });
    }

    res.json({ orders: customer.orders });
  } catch (error) {
    console.error('Error retrieving orders:', error);
    res.status(500).json({ message: 'An error occurred while retrieving orders' });
  }
});
```
5. Create an API to retrieve a list of customers who have not made any purchases in the last 3 months based on the orderDate field in the customer collection.

```
// Retrieve list of customers who haven't purchased in the last 3 months
app.get('/inactive-customers', async (req, res) => {
  const threeMonthsAgo = new Date();
  threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);

  try {
    const inactiveCustomers = await Customer.find({
      orders: { $not: { $elemMatch: { orderDate: { $gte: threeMonthsAgo } } } }
    });

    res.json({ inactiveCustomers });
  } catch (error) {
    console.error('Error retrieving inactive customers:', error);
    res.status(500).json({ message: 'An error occurred while retrieving inactive customers' });
  }
});
```