node.js - 在 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;
}
解决方案
我所做的只是将我所有的路线都投入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"));
})();
推荐阅读
- c# - C# Visual Studio 项目属性和 MSBuild 宏
- perl - Perl:构建没有预定义数量的键列的哈希?
- javascript - 从数组中删除重复的对象
- python - 更改数据框的日期格式
- python - 无法在 Google Cloud Console 上上传 python 脚本。(错误响应 [13] && 错误响应 [9])
- spring - 通过 Spring Boot 启动器包含配置文件
- scala - 如何在 Spark 2.3.0 UDF 中为每个工作人员构造和持久化一个引用对象?
- java - 无法让活动兼容工作
- java - 通过 JDBC 语句执行 DDL 时出错和我找不到的语法错误
- php - 当购物车重量超过 Woocommerce 中的特定限制时的自定义消息