Untitled
unknown
plain_text
a year ago
1.4 kB
2
Indexable
Never
import express, { Request, Response } from 'express'; import mongoose, { Document, Model } from 'mongoose'; // Define a Mongoose schema and model interface Item extends Document { timestamp: Date; name: string; } const itemSchema = new mongoose.Schema({ timestamp: { type: Date, default: Date.now }, name: String, }); const ItemModel: Model<Item> = mongoose.model('Item', itemSchema); const app = express(); const port = 3000; app.use(express.json()); // Create a new item app.post('/items', async (req: Request, res: Response) => { try { const newItem = new ItemModel(req.body); await newItem.save(); res.json(newItem); } catch (error) { res.status(500).json({ error: 'Could not create the item' }); } }); // Get all items sorted by timestamp (ascending) app.get('/items', async (req: Request, res: Response) => { try { const items = await ItemModel.find().sort({ timestamp: 1 }); res.json(items); } catch (error) { res.status(500).json({ error: 'Could not retrieve items' }); } }); // Start the server app.listen(port, () => { console.log(`Server is running on port ${port}`); }); mongoose.connect('mongodb://localhost/sort-api', { useNewUrlParser: true, useUnifiedTopology: true, }); const db = mongoose.connection; db.on('error', console.error.bind(console, 'Connection error:')); db.once('open', () => { console.log('Connected to the database'); });