我几乎完成了我的应用程序,我想连接我的MongoDB数据库到无服务器平台MongoDB Atlas。直到那时,我一直在使用我的数据库在localhost(与mongosh),它工作得非常好。现在我已经改变了“mongodb://localhost”到我的数据库的地址,我得到一个错误:MongoNotConnectedError: MongoNotConnectedError: MongoClient必须连接执行这个操作
下面是我在db-connection。js中的代码:
require('dotenv').config();
let { MongoClient } = require('mongodb');
function connect(collection) {
let client = new MongoClient(`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@calendrier-delle.2rqpi.mongodb.net/calendrierdelle?retryWrites=true&w=majority`);
client.connect();
let calendrierDelle = client.db('calendrierdelle');
let collections = calendrierDelle.collection(`${collection}`);
return collections;
}
module.exports = { connect };
和我的代码片段在server。js:
require('dotenv').config();
let express = require("express");
let app = express();
let dbConnection = require("./db-connection.js");
//Here is an example of how I make an query
let query = dbConnection.connect("aCollection").find({
something: (some value),
}).toArray();
query.then((data) => { /* Do something with the data */ });
精确:
? 我不用猫鼬,因为我真的不需要,而且我懒得换。
? 在MongoDB Atlas上,我添加了一个IP地址0。0。0。0/0
? 我的用户名和密码是商品
? 下面是我的集群名称和db名称的截图
在我的代码连接我的数据库,我真的不明白为什么在url的末尾我连接我的应用程序与数据库,之后我必须做同样的事情:客户端。db('calendrierdelle')。我认为这是我的问题,但我不知道如何解决它:我已经尝试了一切(更改url省略我的calendrierDelle变量等…)。
你能帮帮我吗?谢谢!
PS:对不起,我添加了一个猫鼬标签,我不使用它,但它非常接近我的问题。
###JavaScript是异步的,这意味着动作不会在完成之前等待动作。你试图在没有等待MongoDB连接的情况下对数据库做一些事情。幸运的是,MongoDB不会让promise和async
/await
. You can make things "wait" for Mongo to connect like so:
await
.. 你可以像这样让事情“等待”Mongo连接:
require('dotenv').config();
let { MongoClient } = require('mongodb');
async function connect(collection) {
let client = new MongoClient(`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@calendrier-delle.2rqpi.mongodb.net/calendrierdelle?retryWrites=true&w=majority`);
await client.connect();
let calendrierDelle = client.db('calendrierdelle');
let collections = calendrierDelle.collection(`${collection}`);
return collections;
}
module.exports = { connect };
注意client。connect()前面的await。还要注意,connect函数前面有async。直到最新版本的NodeJS await必须在一个异步函数中。
###
require('dotenv').config();
let { MongoClient } = require('mongodb');
const url =
`mongodb+srv://${process.env.DB_USER}:${process.env.DB_USER_PASSWORD}@
${process.env.DB_CLUSTER}.mongodb.net`;
async function connectDatabase() {
const client = await MongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = client.db("main");
return {
listings: db.collection("test_listings")
};
};
module.exports = { connectDatabase };