小编Eth*_*han的帖子

NodeJS 类结构中的 MongoDB

有没有办法在 NodeJS 的类结构中使用 MongoDB?

我知道您可以在连接方法中对数据库进行 CRUD 操作,例如

mongo.connect(url, function(err, client){//do some CRUD operation});

但我想知道是否有办法打开与数据库的连接,可以在整个班级中访问它,然后在完成班级工作后关闭它。

例如:

class MyClass {
    constructor(databaseURL) {
      this.url = databaseURL;
    }

    async init() {
      //make connection to database
    }

    async complete_TaskA_onDB() {
      //...
    }

    async complete_TaskB_onDB() {
      //...
    }

    async close_connection() {
      //close connection to database
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

我刚刚在Node.JS Mongo 文档中发现了更多信息。也许类似的东西会起作用?

//constructor()
this.db = new MongoClient(new Server(dbHost, dbPort));

//init()
this.db.open();

//taskA()
this.db.collection(...).update(...);

//close_connection()
this.db.close();
Run Code Online (Sandbox Code Playgroud)

mongodb node.js

5
推荐指数
1
解决办法
5250
查看次数

标签 统计

mongodb ×1

node.js ×1