Quick tutorial on how to use MongoDB & Mongoose on nodejs (get & post request)
Edrick Ee
Posted on August 14, 2021
install mongoose: npm install -S mongoose
connect mongoose: const mongoose = require('mongoose');
connect: mongoose.connect(server/databaselocation)
const mongoose = require('mongoose');
const mongoURI = 'mongodb://localhost:9999/test';
const db = mongoose.connect(mongoURI, { useNewUrlParser: true });
db
.then(db => console.log(`Connected to: ${mongoURI}`))
.catch(err => {
console.log(`There was a problem connecting to mongo at: ${mongoURI}`);
console.log(err);
});
module.exports = db;
set up model: mongoose.model('collectionName', {name: String})
const mongoose = require('mongoose');
const attendeeSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
shirt: String,
skillLevel: String
});
const Attendee = mongoose.model('Attendee', attendeeSchema);
module.exports = Attendee;
make get request to the collection
app.get('/attendees', (req, res) => {
Attendee.find(function(err, Attendee) {
res.send(Attendee);
})
});
make post request to the collection
app.post('/attendees', (req, res) => {
var post = new Attendee ({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
shirt: req.body.shirt,
skillLevel: req.body.skillLevel
})
post.save(function (err, post) {
if (err) {
return next(err)
}
res.send(201)
console.log('successfully updated')
})
});
Quick tutorial for Mongoose: https://www.youtube.com/watch?v=5e1NEdfs4is
💖 💪 🙅 🚩
Edrick Ee
Posted on August 14, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.