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}`);
});
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' });
}
});
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' });
}
});
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)