Last active
May 18, 2020 11:28
-
-
Save vaibhavgeek/a2fd9535c3a4f98bf07a4dc4a8e1f3fb to your computer and use it in GitHub Desktop.
Your First SPA in ReactJs, NodeJS
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
const mongoose = require('mongoose'); | |
const Schema = mongoose.Schema; | |
let Article = new Schema({ | |
content: { | |
type: String | |
}, | |
author: { | |
type: String | |
} | |
}); | |
module.exports = mongoose.model('Article', Article); |
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
const express = require('express'); | |
const app = express(); | |
const bodyParser = require('body-parser'); | |
const cors = require('cors'); | |
const mongoose = require('mongoose'); | |
const articleRoutes = express.Router(); | |
const PORT = 4000; | |
let article = require('./article.model'); | |
app.use(cors()); | |
app.use(bodyParser.json()); | |
mongoose.connect('mongodb://127.0.0.1:27017/articles', { useNewUrlParser: true }); | |
const connection = mongoose.connection; | |
connection.once('open', function() { | |
console.log("MongoDB database connection established successfully"); | |
}) | |
articleRoutes.route('/articles/').get(function(req, res) { | |
article.find(function(err, art) { | |
if (err) { | |
console.log(err); | |
} else { | |
res.json(art); | |
} | |
}); | |
}); | |
articleRoutes.route('/article/:id').get(function(req, res) { | |
let id = req.params.id; | |
article.findById(id, function(err, article) { | |
res.json(article); | |
}); | |
}); | |
articleRoutes.route('/article/update/:id').post(function(req, res) { | |
Article.findById(req.params.id, function(err, art) { | |
if (!art) | |
res.status(404).send("data is not found"); | |
else | |
art.content = req.body.content; | |
art.author = req.body.author; | |
art.save().then(todo => { | |
res.json('Article updated!'); | |
}) | |
.catch(err => { | |
res.status(400).send("Update not possible"); | |
}); | |
}); | |
}); | |
articleRoutes.route('/article/new').post(function(req, res) { | |
let article = new article(req.body); | |
article.save() | |
.then(article => { | |
res.status(200).json({'article': 'article added successfully'}); | |
}) | |
.catch(err => { | |
res.status(400).send('adding new article failed'); | |
}); | |
}); | |
app.use('/', articleRoutes); | |
app.listen(PORT, function() { | |
console.log("Server is running on Port: " + PORT); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment