Created
May 17, 2016 02:03
-
-
Save jimmycann/ca8a861a27e2216fc50cdc95c53f7dad to your computer and use it in GitHub Desktop.
Simple NodeJS API - CRUD using Mongoose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Keyless - Should be integrated with authentication | |
//Need to require this file from your Express config using: | |
//require('./routes.js')(app); | |
var mongoose = require('mongoose'); | |
var Blog = mongoose.model('blog', { | |
title: String, | |
subtitle: String, | |
img: String, | |
content: String, | |
slug: String, | |
active: { type: Boolean, default: true }, | |
created: { type: Date, default: Date.now } | |
}); | |
function blogApi(res) { | |
Blog.find(function (err, blog) { | |
if (err) { | |
res.send(err); | |
} | |
res.json(blog); | |
}); | |
} | |
module.exports = function (app) { | |
//Create | |
app.post('/api/create-blog', function (req, res) { | |
var slug = convertToSlug(req.body.title); | |
Blog.create({ | |
active: req.body.active, | |
title: req.body.title, | |
subtitle: req.body.subtitle, | |
img: req.body.img, | |
slug: slug, | |
content: req.body.content | |
}, function (err, blog) { | |
if (err) | |
res.send(err); | |
blogApi(res); | |
}); | |
}); | |
//Retrieve | |
app.get('/api/get-blogs', function (req, res) { | |
blogApi(res); | |
}); | |
//Update | |
app.post('/api/update-blog', function (req, res) { | |
var slug = convertToSlug(req.body.title); | |
console.log(req.body); | |
Blog.update({ | |
_id: req.body._id | |
}, | |
{ | |
active: req.body.active, | |
title: req.body.title, | |
subtitle: req.body.subtitle, | |
img: req.body.img, | |
slug: slug, | |
content: req.body.content | |
}, function (err, blog) { | |
if (err) | |
res.send(err); | |
blogApi(res); | |
}); | |
}); | |
//Delete | |
app.post('/api/delete-blog', function (req, res) { | |
Blog.remove({ | |
_id: req.body._id | |
}, function (err, blog) { | |
if (err) | |
res.send(err); | |
blogApi(res); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment