Skip to content

Instantly share code, notes, and snippets.

@keif
Created February 11, 2021 14:08
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 keif/3abe1a8d77a8a11354311881ab3e094e to your computer and use it in GitHub Desktop.
Save keif/3abe1a8d77a8a11354311881ab3e094e to your computer and use it in GitHub Desktop.
Mongoose Schema and Express Routes Using Users/Albums using an ugly token example.
var express = require("express")
var app = express()
var bodyParser = require("body-parser")
var mongoose = require("mongoose")
var userSchema = mongoose.Schema({
name: String,
email: String,
password: String,
token: String, // this is for the example code, JWT would be used in a real life scenario
})
var User = mongoose.model("User", userSchema)
var albumSchema = mongoose.Schema({
title: String,
performer: String,
cost: Number,
})
var Album = mongoose.model("Album", albumSchema)
var purchaseSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
album: {
type: mongoose.Schema.Types.ObjectId,
ref: "Album",
},
})
var Purchase = mongoose.model("Purchase", purchaseSchema)
app.use(bodyParser.json())
app.listen(3000)
app.post("/purchases", (req, res) => {
const user = req.body.user
const album = req.body.album
const newPurchase = new Purchase({
user: user,
album: album,
})
newPurchase
.save()
.then((purchase) => {
Purchase.populate(purchase, [{ path: "user" }, { path: "album" }])
.then((purchaseData) => {
return res.json({ data: purchaseData })
})
.catch(console.log)
})
.catch(console.log)
})
app.post("/signup", (req, res) => {
const { name, email, password } = req.body
const newUser = new User({
email: email,
name: name,
password: password,
})
newUser
.save()
.then(() => {
const token = "token" + Math.random()
res.header("authorization", token).status(204).send()
})
.catch((err) => {
console.log("signup error:", err)
return res.status(400).json({ success: false })
})
})
app.post("/logout", (req, res) => {
const filter = { token: req.headers["authorization"] }
const update = { token: null }
User.findOneAndUpdate(filter, update)
delete res.header("authorization")
res.sendStatus(204)
})
app.post("/login", (req, res) => {
const filter = { email: req.body.email }
const token = "token" + Math.random()
const update = { token: token }
User.findOneAndUpdate(filter, update, function (err, user) {
if (!user) {
return res.status(400).json({ success: false })
}
if (user.password !== req.body.password) {
return res.status(400).json({ success: false })
}
res.header("authorization", token).sendStatus(204)
})
})
app.use(function (req, res, next) {
User.findOne({ token: req.headers.authorization })
.then((response) => {
console.log(response, req.headers.authorization)
if (response && response.token === req.headers.authorization) {
next()
} else {
return res.status(401).json({ error: "Not authorized." })
}
})
.catch((err) => {
return res.status(401).json({ error: "Not authorized." })
})
})
app.get("/albums", (req, res) => {
Album.find()
.then((response) => {
res.json({ data: response })
})
.catch((err) => {
res.json({ error: err })
})
})
app.get("/albums/:id", (req, res) => {
Album.findById(req.params.id).then((response) => {
try {
res.json({ data: response })
} catch (err) {
res.json({ Error: err })
}
})
})
app.post("/albums", (req, res) => {
const newPost = Album({
title: req.body.title,
performer: req.body.performer,
cost: req.body.cost,
})
newPost
.save((err) => {
if (err) res.json({ error: err })
})
.then((data) => {
res.json({ data: data })
})
})
app.put("/albums/:id", (req, res) => {
Album.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true },
(err, album) => {
if (err) return res.status(500).send(err)
return res.json({ data: album })
}
)
})
app.delete("/albums/:id", (req, res) => {
const id = req.params.id
Album.findById(id).then((docs) => {
docs.remove()
res.status(204).json({ data: docs })
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment