Created
December 17, 2018 01:01
-
-
Save KustomDeveloper/cf48e3dd641729fd0db1ab585a26844f to your computer and use it in GitHub Desktop.
Basic node.js crud app using: node.js, mongoose.js, express.js, and nodemon.js on an mlab mongo db server
This file contains hidden or 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
| //Require assets | |
| const express = require('express'); | |
| const app = express(); | |
| const mongoose = require('mongoose'); | |
| mongoose.Promise = global.Promise; | |
| let port = 3000; | |
| const bodyParser = require('body-parser'); | |
| app.use(bodyParser.json()); | |
| app.use(bodyParser.urlencoded({ extended: true })); | |
| //Add username and password credentials to connect to db - I use mlab.com for a database service | |
| mongoose.connect( | |
| 'mongodb://<username>:<password>@ds135714.mlab.com:35714/around-town', | |
| { useNewUrlParser: true } | |
| ); | |
| var db = mongoose.connection; | |
| db.on('error', console.error.bind(console, 'connection error:')); | |
| db.once('open', function() { | |
| console.log('Connected!'); | |
| }); | |
| //Listen on port 3000 | |
| app.listen(port, () => { | |
| console.log('Server listening on port ' + port); | |
| }); | |
| var eventSchema = mongoose.Schema({ | |
| eventName: String, | |
| }) | |
| var eventData = mongoose.model('Event', eventSchema); | |
| //Load index page using endpoint | |
| app.get('/', (req, res) => { | |
| res.sendFile(__dirname + '/index.html'); | |
| }); | |
| //Save data | |
| app.post('/event', (req, res) => { | |
| let userData = new eventData({ | |
| eventName: req.body.eventName | |
| }) | |
| userData.save() | |
| .then((data) => { | |
| res.send('item saved to database') | |
| console.log(data); | |
| }) | |
| .catch((err) => { | |
| res.status(400).send('unable to save to database'); | |
| console.log(err); | |
| }); | |
| }); | |
This file contains hidden or 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
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>Add a local event</title> | |
| </head> | |
| <body> | |
| <div class="app"> | |
| <h1>Add an events</h1> | |
| <form method="post" action="/event"> | |
| <label>Enter event Name</label><br> | |
| <input type="text" name="eventName" placeholder="Enter event name..." required> | |
| <input type="submit" value="Add Event"> | |
| </form> | |
| </div> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment