Skip to content

Instantly share code, notes, and snippets.

@VRamazing
Created March 13, 2025 11:40
Show Gist options
  • Save VRamazing/10a4600af20f351770fb64a83935682c to your computer and use it in GitHub Desktop.
Save VRamazing/10a4600af20f351770fb64a83935682c to your computer and use it in GitHub Desktop.
Mongoose Schema and queries
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
// Set mongoose strictQuery
mongoose.set('strictQuery', true);
// TODO: Connect to MongoDB at 127.0.0.1:27017/library-app
mongoose.connect("mongodb://127.0.0.1:27017/library-app", {
useNewUrlParser: true,
useUnifiedTopology: true
})
// TODO: Define schema for authors
// Structure: name (String, required)
const authorSchema = mongoose.Schema({
name: {type: String, required: true}
})
// TODO: Define schema for books with a reference to authors
// Structure: title (String, required), author (ObjectId, ref to Author)
const bookSchema = mongoose.Schema({
title: { type: String, required: true },
author: {type: mongoose.Schema.Types.ObjectId, ref: "Author"}
})
// TODO: Create models for Author and Book
const Author = mongoose.model("Author1", authorSchema)
const Book = mongoose.model("Book", bookSchema)
// TODO: Create GET /authors and POST /authors routes
// For POST /authors, the request body should contain a "name" field, e.g., { name: "Author Name" }
app.get("/authors", async (req, res) => {
const authors = await Author.find()
res.send(authors)
})
app.post("/authors", async (req, res) => {
try {
const {name} = req.body;
newAuthor = new Author({name})
savedAuthor = await newAuthor.save()
res.status(201).json(savedAuthor)
} catch(e){
console.error(e.message)
res.status(400).json(e.message)
}
})
// TODO: Create GET /books and POST /books routes
// For POST /books, the request body should contain "title" and "author" fields, e.g., { title: "Book Title", author: "Author ObjectId" }
app.get("/books", async (req, res) => {
const books = await Book.find().populate("author")
res.send(books)
})
app.post("/books", async (req, res) => {
try {
const {title, author} = req.body
newBook = new Book({title, author})
savedBook = await newBook.save()
res.status(201).json(savedBook)
} catch(e){
console.error(e.message)
res.status(400).json(e.message)
}
})
// TODO: Error handling middleware
app.use((err, req, res, next) => {
if(err) console.err(err)
res.status(500).send("Something Broke")
})
// TODO: Start Express server on port 3000
app.listen(PORT, () => {
console.log("Running on port", PORT)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment