david.dev


MongoJS: Express quick guide

23/12/2020

#mongodb, #nodejs, #express


I have spent some time with MongoJS and I quickly noticed that some of the easy operations like delete and update records are not very clearly laid out in the readme so here is my quick guide on how to use MongoJS with Express:

Connection

var mongojs = require('mongojs')
var db = mongojs('yourDB', ['yourCollection'])

Insert one record

db.yourCollection.insert({title: req.body.title, slug: req.body.slug,intro:req.body.intro,
body:req.body.body, date:new Date()})
res.render('form', {message:"page added🪶"});

Delete Record

This was tricky as I couldn't find anything about it on the readme

router.get('/article-delete/:id', function(req, res, next) {
let id = req.params.id;
db.posts.remove({ _id:mongojs.ObjectId(id)}, function(err, doc2) {
res.render('form', { message:"deleted!", doc:""});
  })

Update Record

db.posts.updateOne({ _id:mongojs.ObjectId(req.body.id)}, { $set: { title: req.body.title, slug: req.body.slug,
intro:req.body.intro, body:req.body.body}}, function (err,doc) {
      // the update is complete
      console.log(err)
      console.log (doc)
      res.render('form', {message:"page edited🪶"});
  })

So this is it, you now have a quick guide to get started with MongoJS and Express! 🚄