首页 > 解决方案 > 在 MVC Express 应用程序中创建数据库服务

问题描述

我正在创建一个 Node / Express / Mongo 应用程序,并希望有一个 MVC 样式的文件布局和一个单独的数据库服务。我希望我的路由(控制器)相当精简,并且当我需要执行 CRUD 功能时只需从其他地方调用方法。

这篇很棒的帖子有很多可靠的答案。我将粘贴在EddieDean的答案下方,该答案似乎与我想做的最接近。

但是,当我尝试mongo.js在我的文件中引用文件中定义的用户对象时someFile.js,它返回为未定义。 我很确定我遗漏了一些明显的东西,并且很想知道那是什么。

我可以获得对数据库连接本身的引用并调用dbConn.Users.addUser(x),但我不能直接调用Users.addUser(x),如下someFile.js例所示。

这似乎微不足道,但我花了太多时间没有答案。称之为知识仇杀。

谢谢。


mongo.js

const { MongoClient } = require('mongodb');
const config = require('./config');
const Users = require('./Users');
const conf = config.get('mongodb');

class MongoBot {
  constructor() {
    const url = `mongodb://${conf.hosts.join(',')}`;

    this.client = new MongoClient(url, conf.opts);
  }
  async init() {
    await this.client.connect();
    console.log('connected');

    this.db = this.client.db(conf.db);
    this.Users = new Users(this.db);
  }
}

module.exports = new MongoBot();

用户.js

class User {
  constructor(db) {
    this.collection = db.collection('users');
  }
  async addUser(user) {
    const newUser = await this.collection.insertOne(user);
    return newUser;
  }
}
module.exports = User;

应用程序.js

const mongo = require('./mongo');

async function start() {
  // other app startup stuff...
  await mongo.init();
  // other app startup stuff...
}
start();

一些文件.js

const { Users } = require('./mongo');

async function someFunction(userInfo) {
  const user = await Users.addUser(userInfo);
  return user;
}

标签: node.jsmongodbexpressmodel-view-controller

解决方案


我所做的只是将我所有的路线都投入start使用。这不是最好的解决方案,但作为起点至少不是最差的。因此,每当您需要从某个 js 文件访问数据库时,只需将它们放入start,这样就mongo可以先建立连接。

所以我想在/routes/users文件中获取数据库实例。

const express = require("express");
const mongo = require("./mongo");
const app = express();
const PORT = process.env.PORT || 3000;

(async function start() {
  await mongo.init();

  app.use("/users", require("./routes/user")); 
})();

推荐阅读