javascript - TypeError:尝试使用 Mongodb Atlas Online 时无法读取未定义的属性“db”
问题描述
[nodemon] 启动node server.js
C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\utils.js:725 抛出错误;^
类型错误:无法读取 C:\Users\Abhay\Desktop\todo-app\server.js:8:17 在 C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib 处未定义的属性“db” \utils.js:722:9 在 C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\mongo_client.js:223:23 在 C:\Users\Abhay\Desktop\todo-app\node_modules \mongodb\lib\operations\connect.js:279:21 在 QueryReqWrap.callback (C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\core\uri_parser.js:56:21) 在 QueryReqWrap .onresolve [as oncomplete] (dns.js:202:10) [nodemon] 应用程序崩溃 - 在开始之前等待文件更改...
let express = require('express')
let mongodb = require('mongodb')
let app = express()
let db
let connectionString = 'mongodb+srv://todoAppUser:kTL7PYesKzfB6FMz@cluster0.fif5n.mongodb.net/TodoApp?retryWrites=true&w=majority'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
db = client.db()
app.listen(3000)
})
解决方案
您似乎正在尝试使用MongoClient的静态连接方法来连接到您的数据库,但您没有使用 MongoClient 类本身。
要连接到任何数据库,您将需要一个连接的 MongoClient 实例。使用静态连接方法,可以通过以下方式实现:
const mongodb = require("mongodb");
const connectionURL = "mongodb+srv://your-connection-srv-here"
const dbName = "your_db_name"
//get MongoClient
const MongoClient = mongodb.MongoClient;
let db = null;
MongoClient.connect(connectionURL,{
useNewUrlParser: true,
useUnifiedTopology: true
},(err,connectedClient) => {
if(err){
throw err;
}
//connectedClient will be the connected instance of MongoClient
db = connectedClient.db(dbName);
//now you can write queries
db.collection("your_collection").find({}).toArray()
.then(r => {
console.log(r);
}).catch(e => {
console.error(`ERROR:`,e);
})
})
但是,使用回调会很麻烦。根据上面链接的文档,如果未传递回调函数,Node.js 的 MongoDb 驱动程序中的大多数函数都会返回一个 Promise ,这非常方便。使用它,您可以编写一个函数,该函数返回一个将连接的实例解析到您的数据库的承诺。
const MongoClient = require('mongodb').MongoClient;
/*
we draw the connection srv and the db name from the config to return just one instance of that db.
Now this function call be called wherever a connection is needed
*/
const getDbInstance = (config) => new Promise((resolve,reject) => {
const client = new MongoClient(config.dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true
});
client.connect((error) => {
if(error){
console.error(error);
reject(error);
}
let db = client.db(config.dbName);
resolve(db);
})
})
const doSomeDbOperations = async() => {
//hardcoding it here, but this config will probably come from environment variables in your project
const config = {
dbUrl: "mongodb+srv://your-connection-srv-here",
dbName: "your_db_name"
};
try{
const db = await getDbInstance(config);
//do whatever querying you wish here
}catch(e){
console.error(`ERROR: `,e);
}
}
doSomeDbOperations();
推荐阅读
- bitbucket - 复选框不适用于 Bitbucket 中的降价
- css-transitions - 转换停止使用 fullpage.js
- java - 运行 savina 代码 https://github.com/shamsimam/savina
- java - 如何在 JAVA 中使用 JAXB 正确生成 XML
- python - 如何根据状态用 Python 总结范围?
- vscode-settings - 如何在调试模式下更改当前断线颜色?
- scripting - AHK 如何修复 KeyPress 没有打破循环
- c - 将结构保存在 bin 文件中后如何删除它的内容?
- xpath - 我想为两个 Web 元素编写相对 Xpath
- sql - 插入和不存在的插入之间的性能差异