Quick tutorial on how to use MongoDB & Mongoose on nodejs (get & post request)

ehdtlaos

Edrick Ee

Posted on August 14, 2021

Quick tutorial on how to use MongoDB & Mongoose on nodejs (get & post request)
  1. install mongoose: npm install -S mongoose

  2. connect mongoose: const mongoose = require('mongoose');

  3. 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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

make get request to the collection

app.get('/attendees', (req, res) => {
  Attendee.find(function(err, Attendee) {
    res.send(Attendee);
  })
});
Enter fullscreen mode Exit fullscreen mode

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')
  })
});
Enter fullscreen mode Exit fullscreen mode

Quick tutorial for Mongoose: https://www.youtube.com/watch?v=5e1NEdfs4is

💖 💪 🙅 🚩
ehdtlaos
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.

Related