mardi 2 juin 2020

Node.js Mongodb Native Driver folder Structure

I have worked with Mongoose and aware of multiple folder structures for better code management. I started on a new project in which performance is the key and after 5-6 hours of research, I found that MongoDB native driver is faster then mongoose. The native driver is completely new to me and I have no idea of any folder structure or patterns.

I tried to find projects using MongoDB Native library on GitHub and tutorials on the web but almost all of them use mongoose.

What is better folder structure with MongoDB Native driver for production? Any sample projects on GitHub for reference?

Here is a messy sample code from the controller which I need to organise.

PS: I know this code structure is a piece of crap :(.

const  config = require("../config.js"),
       jwt = require("jwt-simple"),
       MongoClient = require("mongodb").MongoClient,
       assert = require("assert");
//Bcrypt
const bcrypt = require("bcrypt");
const saltRounds = 10;
const myPlaintextPassword = "s0//P4$$w0rD";
const someOtherPlaintextPassword = "not_bacon";

//DB COnnection
const url = "mongodb://localhost/sb";
const dbName = "sb";

//Useful Function
const findDocuments = function (db, user, callback) {
  // Get the documents collection
  const collection = db.collection("users");
  // Find some documents
  collection.find({ username: user }).toArray(function (err, docs) {
    assert.equal(err, null);
    console.log("Found the following recordssss");
    callback(docs);
  });
};

const insertDocuments = function (db, data, callback) {
  // Get the documents collection
  const collection = db.collection("users");
  // Insert some documents
  collection.insertOne(data, function (err, result) {
    assert.equal(err, null);
    console.log("Inserted 1 documents into the collection");
    callback(result);
  });
};

exports.login = function (req, res) {
  const client = new MongoClient(url);
  client.connect(function (err) {
    assert.equal(null, err);
    console.log("Connected correctly to server");
    const db = client.db(dbName);
    findDocuments(db, req.body.username, function (user) {
      console.log(user);
      if (!user) {
        console.log("NoUserFound");
      } else {
        console.log(req.body.password);
        console.log(user.hash);
        bcrypt.compare(req.body.password, user[0].hash, function (err, result) {
          client.close();

          if (result) {
            var payload = {
              id: user.id,
              expire: Date.now() + 1000 * 60 * 60 * 24 * 7, //7 days
            };
            var token = jwt.encode(payload, config.jwtSecret);
            res.json({
              token: token,
            });
          } else {
            res.send("UNAUTHORIZED");
          }
        });
      }
    });
  });
};
exports.register = function (req, res) {
  bcrypt.hash(req.body.password, saltRounds, function (err, hash) {
    const client = new MongoClient(url);

    client.connect(function (err) {
      assert.equal(null, err);
      console.log("Connected correctly to server");
      const db = client.db(dbName);
      insertDocuments(
        db,
        { name: req.body.name, username: req.body.username, hash: hash },
        (data) => {
          client.close();
          res.send(data);
        }
      );
    });
  });

Aucun commentaire:

Enregistrer un commentaire