存储 MongoClient.connect()
Store MongoClient.connect()
我在做一个代码被分成多个js文件的项目。到目前为止,我已经多次调用 MongoClient.connect()
(在每个使用数据库的文件中)。那是我收到多个弃用警告的时候:
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
我很快发现它与所有这些打开的连接有关。即使我可以将 MongoClient 存储在单独的文件中,我如何存储 MongoClient.connect()
,因为使用数据库的代码看起来像那:
MongoClient.connect((err) => {
// code here
});
不是这样的:
MongoClient.connect()
// code here
编辑: 好吧,它似乎有效,但看起来文件的导出等于 {}
...
问题似乎可以通过将连接放在一个单独的文件中来解决(是的,我终于知道怎么做了!)。
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();
});
});
使用数据库的其他文件
const mongo = require("./mongoClient")
const collection = mongo.db("niceDB").collection("coolCollection")
collection.findOne({fancy: "document"}); // It works!
我在做一个代码被分成多个js文件的项目。到目前为止,我已经多次调用 MongoClient.connect()
(在每个使用数据库的文件中)。那是我收到多个弃用警告的时候:
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
我很快发现它与所有这些打开的连接有关。即使我可以将 MongoClient 存储在单独的文件中,我如何存储 MongoClient.connect()
,因为使用数据库的代码看起来像那:
MongoClient.connect((err) => {
// code here
});
不是这样的:
MongoClient.connect()
// code here
编辑: 好吧,它似乎有效,但看起来文件的导出等于 {}
...
问题似乎可以通过将连接放在一个单独的文件中来解决(是的,我终于知道怎么做了!)。
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();
});
});
使用数据库的其他文件
const mongo = require("./mongoClient")
const collection = mongo.db("niceDB").collection("coolCollection")
collection.findOne({fancy: "document"}); // It works!