lookup request in database and serve object as json in typescript

Assuming there's a mongoose model defined for the object you want to serve, first install the required packages:

index.ts
npm install --save express mongoose
36 chars
2 lines

Then import the required packages and connect to the mongoose database:

index.ts
import express, { Request, Response } from 'express';
import mongoose from 'mongoose';

// Connect to mongoose database
mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
236 chars
9 lines

Next, create an express route to handle the request and lookup the object in the database:

index.ts
// Define express router
const router = express.Router();

// Define mongoose schema and model
const mySchema = new mongoose.Schema({
  name: String,
  age: Number,
});
const MyModel = mongoose.model('MyModel', mySchema);

// Define express route handler
router.get('/myroute/:id', async (req: Request, res: Response) => {
  // Lookup object in database by id
  const myObject = await MyModel.findById(req.params.id);

  // If object not found, return 404 error response
  if (!myObject) {
    return res.status(404).json({ error: 'Not found' });
  }

  // Serve object as JSON response
  res.json(myObject.toJSON());
});
622 chars
24 lines

Finally, mount the router in your express app:

index.ts
// Create express app and mount router
const app = express();
app.use('/api', router);

// Start express server
app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
189 chars
9 lines

This will create an express app with a router that handles GET requests to /api/myroute/:id. When a request is received, the corresponding object is looked up in the database by id and served as a JSON response.

gistlibby LogSnag