NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
// Add other user fields as needed
});

module.exports = mongoose.model('User', userSchema);




const mongoose = require('mongoose');

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

module.exports = mongoose.model('Product', productSchema);





const mongoose = require('mongoose');

const orderSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
products: [
{
product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true },
quantity: { type: Number, required: true },
},
],
totalAmount: { type: Number, required: true },
// Add other order fields as needed
});

module.exports = mongoose.model('Order', orderSchema);








const mongoose = require('mongoose');

const transactionSchema = new mongoose.Schema({
order: { type: mongoose.Schema.Types.ObjectId, ref: 'Order', required: true },
paymentMethod: { type: String, required: true },
transactionAmount: { type: Number, required: true },
// Add other transaction fields as needed
});

module.exports = mongoose.model('Transaction', transactionSchema);






Now, let's create the routes and controllers:
src/routes/orders.js
const express = require('express');
const router = express.Router();
const Order = require('../models/order');
const Transaction = require('../models/transaction');

// 1. Place Order
router.post('/', async (req, res) => {
try {
const { user, products, totalAmount } = req.body;
const order = new Order({ user, products, totalAmount });
const savedOrder = await order.save();

res.status(201).json(savedOrder);
} catch (err) {
res.status(400).json({ error: err.message });
}
});

// 2. Get Order Details
router.get('/:id', async (req, res) => {
try {
const order = await Order.findById(req.params.id)
.populate('user', 'name email')
.populate('products.product', 'name description price');

if (!order) {
return res.status(404).json({ error: 'Order not found' });
}

res.json(order);
} catch (err) {
res.status(500).json({ error: err.message });
}
});

// 3. Get Transaction Details
router.get('/:id/transaction', async (req, res) => {
try {
const transaction = await Transaction.findOne({ order: req.params.id })
.populate('order', 'totalAmount')
.populate({
path: 'order',
populate: {
path: 'products.product',
model: 'Product',
select: 'name description price',
},
});

if (!transaction) {
return res.status(404).json({ error: 'Transaction not found' });
}

res.json(transaction);
} catch (err) {
res.status(500).json({ error: err.message });
}
});

module.exports = router;






src/app.js
const express = require('express');
const mongoose = require('mongoose');
const ordersRouter = require('./routes/orders');

const app = express();
app.use(express.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost/e-commerce', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('MongoDB connected'))
.catch((err) => console.error('MongoDB connection error:', err));

// Routes
app.use('/api/orders', ordersRouter);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Here's how the APIs work:

Place Order

Send a POST request to /api/orders with the user, products, and totalAmount in the request body.
A new order document will be created in the orders collection, with references to the user and products.


Get Order Details

Send a GET request to /api/orders/:id, replacing :id with the ID of the order.
The response will include the order details, with the user and product details populated using MongoDB's population feature.


Get Transaction Details

Send a GET request to /api/orders/:id/transaction, replacing :id with the ID of the order.
The response will include the transaction details, with the order details and product details populated using MongoDB's population feature.



Note that in this example, we assume that the transaction is created separately after placing the order. You may need to modify the code to suit your application's logic.
Also, remember to handle authentication, authorization, and input validation in a production environment.



     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.