Untitled

mail@pastecode.io avatar
unknown
plain_text
21 days ago
1.3 kB
1
Indexable
Never
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

// MongoDB connection setup
mongoose.connect('mongodb://localhost:27017/brewery_reviews_db', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
    console.log('Connected to MongoDB');
});

// Define schema and model for reviews
const reviewSchema = new mongoose.Schema({
    breweryId: String,
    rating: Number,
    description: String
});
const Review = mongoose.model('Review', reviewSchema);

// API endpoint to save reviews
app.post('/api/reviews', async (req, res) => {
    try {
        const { breweryId, rating, description } = req.body;
        const newReview = new Review({ breweryId, rating, description });
        await newReview.save();
        res.status(201).json({ message: 'Review added successfully' });
    } catch (err) {
        console.error('Error adding review:', err);
        res.status(500).json({ error: 'Error adding review' });
    }
});

app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});
Leave a Comment