简体   繁体   English

存储 MongoClient.connect()

[英]Store MongoClient.connect()

I work on a project whose code is divided into multiple js files.我从事一个项目,其代码分为多个 js 文件。 Until now, I 've been calling MongoClient.connect() multiple times (in each file using the db).直到现在,我一直在调用MongoClient.connect()多次(在每个文件中使用 db)。 That's when I got multiple deprecation warnings:那是我收到多个弃用警告的时候:

the options [servers] is not supported
the options [caseTranslate] is not supported
the options [dbName] is not supported
the options [srvHost] is not supported
the options [credentials] is not supported

I quickly found out it was related to all these open connections.我很快发现它与所有这些打开的连接有关。 Even though I can store MongoClient in a separate file, how can I store MongoClient.connect() , since a code that uses the database looks like that:即使我可以将 MongoClient 存储在单独的文件中,我如何存储MongoClient.connect() ,因为使用数据库的代码如下所示:

MongoClient.connect((err) => {
    // code here
});

and not like that:而不是这样:

MongoClient.connect()
// code here

EDIT: well, it seemed to work, but it looks like the exports of the file are equal to {} ...编辑:嗯,它似乎工作,但看起来文件的导出等于{} ...


The problem seems to be solved by putting the connection in a separate file (yes, I finally found out how to do it.).问题似乎通过将连接放在单独的文件中来解决(是的,我终于找到了如何做到这一点。)。

mongoClient.js mongoClient.js

require("dotenv").config();

// Declaring and configuring the mongoDB client
const { MongoClient } = require("mongodb");
const mongo = new MongoClient(process.env.MONGO_AUTH, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});

mongo.connect((err, result) => { // note the 'result':

    // result == mongo ✅

    // Exports the connection
    module.exports = result;

    // Logs out if the process is killed
    process.on("SIGINT", function () {
        mongo.close();
    });
});

Other file using the db使用 db 的其他文件

const mongo = require("./mongoClient")

const collection = mongo.db("niceDB").collection("coolCollection")
collection.findOne({fancy: "document"}); // It works!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM