Skip to content

Instantly share code, notes, and snippets.

@DragonOsman
Last active November 30, 2022 01:28
Show Gist options
  • Save DragonOsman/7797c11475ef90d953bcd7b1b7a15e28 to your computer and use it in GitHub Desktop.
Save DragonOsman/7797c11475ef90d953bcd7b1b7a15e28 to your computer and use it in GitHub Desktop.
const mongoose = require("mongoose");
const articleSchema = new mongoose.Schema({
title: {
type: String,
required: [true, "Title is required"]
},
content: {
type: String,
required: [true, "Content can't be blank"]
}
});
module.exports = mongoose.model("Article", articleSchema);
const express = require("express");
const router = express.Router();
const Article = require("../models/articles");
router.get("/articles", (req, res) => {
Article.find((err, articles) => res.json(articles));
});
router.get("/articles/:id", (req, res) => {
Article.findById(req.params.id, (err, article) => {
if (!article) {
res.status(404).send("No result found");
} else {
res.json(article);
}
});
});
router.post("/articles", async (req, res) => {
try {
let article = new Article(req.body);
await article.save();
res.send(article);
} catch (err) {
res.status(422).send(`Adding article failed; error: ${err}`);
}
});
router.patch("/articles/:id", async (req, res) => {
try {
await Article.findByIdAndUpdate(req.params.id, req.body);
res.json("Article updated");
} catch (err) {
res.status(422).send(`Article update failed; ${err}`);
}
});
router.delete("/articles/:id", (req, res) => {
Article.findById(req.params.id, async (err, article) => {
if (!article) {
res.status(404).send(`Article not found; ${err}`);
} else {
try {
await Article.findByIdAndRemove(req.params.id)
res.status(200).json("Article deleted");
} catch (err) {
res.status(400).send(`Artice deletion failed; ${err}`)
}
}
});
});
module.exports = router;
const express = require("express");
const mongoose = require("mongoose");
//const cors = require("cors");
const router = require("./routes/index");
const dotenv = require("dotenv").config({ path: `${__dirname}/.env` });
const bodyParser = require("body-parser");
const app = express();
const PORT = 3001;
const MONGO_URI = process.env.MONGO_URI;
//app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.json());
app.use("/api", router);
mongoose.connect(MONGO_URI);
mongoose.connection.once("open", () => console.log("Connected to the Database"));
mongoose.connection.on("error", error => console.log(`Mongoose Connection Error: ${error}`));
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment