Integrating with MongoDB

Connection Setting

  • Set up a cluster from mongo atlas and copy url to driver

const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;

let _db;

const mongoConnect = callback => {
  // database shop will be created automatically
  MongoClient.connect(
    'mongodb+srv://maximilian:9u4biljMQc4jjqbe@cluster0-ntrwp.mongodb.net/shop?retryWrites=true'
  )
    .then(client => {
      console.log('Connected!');
      _db = client.db();
      callback();
    })
    .catch(err => {
      console.log(err);
      throw err;
    });
};

const getDb = () => {
  if (_db) {
    return _db;
  }
  throw 'No database found!';
};

exports.mongoConnect = mongoConnect;
exports.getDb = getDb;

CRUD Operation

const mongodb = require('mongodb');
const getDb = require('../util/database').getDb;

const ObjectId = mongodb.ObjectId;

const db = getDb();

db.collection('products').insertOne({title:"123", ...}).then(result => {
   // ...
}).catch(err => {
   // ...
});

db.collection('products').find().toArray().then(result => {
   // ...
}).catch(err => {
   // ...
});

db.collection('products').findOne({ _id: new ObjectId(prodId) })
      .then(product => {
        console.log(product);
        return product;
      })
      .catch(err => {
        console.log(err);
      });

db.collection('products').updateOne({ _id: new ObjectId(prodId) }, { $set: {...} });

db.collection('products').deleteOne({ _id: new ObjectId(prodId) });

Last updated

Was this helpful?