Skip to content

Instantly share code, notes, and snippets.

@gerardmarquina
Created December 22, 2021 02:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerardmarquina/4c409ceefd8d392fcda0ace588cff187 to your computer and use it in GitHub Desktop.
Save gerardmarquina/4c409ceefd8d392fcda0ace588cff187 to your computer and use it in GitHub Desktop.
Express + mongoose app with simple query on get request with id parameter.
// load libraries
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
// start mongoose with the .env connection string
async function start() {
try {
await mongoose.connect(process.env.CONNECTION);
console.log('Mongoose started');
} catch (e) {
console.log(`Error connecting mongoose ${e}`);
}
}
// start express
async function listen() {
// create app
const express_application = express();
// create film schema
const film_schema = new mongoose.Schema({
id: Number,
name: String
});
// create film model from schema
const film = mongoose.model('Film', film_schema);
// get request with id parameter
express_application.get('/api/v1/films/:id', async (request, response) => {
// search for a film with id = param, if not set to object with status failed
let query = await film.findOne({id : `${request.params.id}`}).exec() || {status: 'failed'};
// send the response
response.status(200).send(query);
});
try {
// server listens to PORT
express_application.listen(process.env.PORT, () => console.log('Express started'));
} catch(e) {
console.log('Error starting express');
}
}
// main function
async function main() {
await start();
await listen();
}
// call main
main().catch( e => console.log(`Unhandled error ${e}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment