Here is an example of how you can add multiple user reviews to a single product using Node.js with Mongoose, Express, and ES6 syntax in a module-based code structure:
- Create a model for the product and user reviews using Mongoose:
// models/Product.js
import mongoose from 'mongoose';
const productSchema = new mongoose.Schema({
name: String,
reviews: [String] // Array of user reviews
});
const Product = mongoose.model('Product', productSchema);
export default Product;
// models/UserReview.js
import mongoose from 'mongoose';
const userReviewSchema = new mongoose.Schema({
content: String,
productId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}
});
const UserReview = mongoose.model('UserReview', userReviewSchema);
export default UserReview;
- Create the route handlers for adding multiple user reviews:
// routes/product.js
import express from 'express';
import Product from '../models/Product';
import UserReview from '../models/UserReview';
const router = express.Router();
router.post('/:productId/reviews', async (req, res) => {
try {
const product = await Product.findById(req.params.productId);
if (!product) {
return res.status(404).json({ message: 'Product not found' });
}
const userReview = new UserReview({
content: req.body.content,
productId: product._id
});
await userReview.save();
product.reviews.push(userReview._id);
await product.save();
res.status(201).json(userReview);
} catch (error) {
res.status(500).json({ message: 'Something went wrong' });
}
});
export default router;
- Set up the router in the main app file:
// app.js
import express from 'express';
import mongoose from 'mongoose';
import productRouter from './routes/product';
const app = express();
mongoose.connect('mongodb://localhost:27017/mydb', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to database');
}).catch((error) => {
console.log('Error connecting to database:', error);
});
app.use(express.json());
app.use('/products', productRouter);
export default app;
- Use the main app file to start the server:
// server.js
import app from './app';
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
With this code, you can send a POST request to /products/:productId/reviews to add a user review to a specific product by providing the content in the request body. The user review will be saved in the UserReview collection, and its reference will be added to the reviews array in the corresponding product document in the Product collection.
Note: Make sure to install the required dependencies: Express, Mongoose, and body-parser.