How to Zinky with MongoDB ?
Last updated: 4 - 5 - 2019


Using MongoDB with Zinky is very simple and intuitive, so let's see how to do it.

Declaring & Attaching to app

We'll start by creating a simple Zinky server:

const Zinky = require('zinky');
var app = new Zinky();

Now, we'll create the MongoDB connection just as we do with other frameworks:

const Zinky = require('zinky');
const mongoClient = require('mongodb').MongoClient;

var url = 'mongodb://username:password@host:port/dbName';
var app = new Zinky();

mongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Connected successfully to database");
});

Now, just attach db to app and listen:

const Zinky = require('zinky');
const mongoClient = require('mongodb').MongoClient;

var url = 'mongodb://username:password@host:port/dbName';
var app = new Zinky();

mongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Connected successfully to database");
  app.db = db;
  app.listen();
});

Use db in modules

In operations

We can access db object in req:

const Zinko = require('zinko');

class Auth extends Zinko {

  async GET_users(req, res) {
    var users = await req.app.db.collection('users').find();
    res.json(users);
  }

}

In non-operation methods

In case we want to access db object in non-action methods, we can find it in this.app:

const Zinko = require('zinko');

class Auth extends Zinko {

  async usernameExists(username) {
    var user = await this.app.db.collection('users').find({username: username});
    return (user) ? true : false;
  }

}

This will lead to an error saying: db is not defined. To solve this we have to add app.loadModules() after attaching db object to app.

So the server file (app.js) will look like this:

const Zinky = require('zinky');
const mongoClient = require('mongodb').MongoClient;

var url = 'mongodb://username:password@host:port/dbName';
var app = new Zinky();

mongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Connected successfully to database");
  app.db = db;
  app.loadModules();
  app.listen();
});

Hope this helped you! If you need any help don't hesitate to ask for it here:https://github.com/zinkyJS/zinky/issues