首页 > 解决方案 > Node.js Mongodb Native Driver 文件夹结构

问题描述

我曾与 Mongoose 合作过,并且知道多个文件夹结构可以更好地管理代码。我开始了一个新项目,其中性能是关键,经过 5-6 小时的研究,我发现 MongoDB 原生驱动程序比 mongoose 更快。本机驱动程序对我来说是全新的,我不知道任何文件夹结构或模式。

我尝试在 GitHub 上查找使用 MongoDB Native 库的项目以及在网络上查找教程,但几乎所有项目都使用 mongoose。

用于生产的 MongoDB 本机驱动程序有什么更好的文件夹结构?GitHub上有任何示例项目供参考吗?

这是我需要组织的控制器中的凌乱示例代码。

PS:我知道这个代码结构是一个废话:(。

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);
        }
      );
    });
  });

标签: node.jsmongodbdesign-patternsstructure

解决方案


推荐阅读