类型错误:在尝试 Mongodb Atlas Online 时无法读取未定义的属性“db" [英] TypeError: Cannot read property 'db' of undefined while trying to Mongodb Atlas Online

查看:42
本文介绍了类型错误:在尝试 Mongodb Atlas Online 时无法读取未定义的属性“db"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[nodemon] 启动 node server.jsC:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\utils.js:725抛出错误;^

[nodemon] starting node server.js C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\utils.js:725 throw error; ^

TypeError: 无法读取未定义的属性 'db'在 C:\Users\Abhay\Desktop\todo-app\server.js:8:17在 C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\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] 应用程序崩溃 - 在启动之前等待文件更改...

TypeError: Cannot read property 'db' of undefined at C:\Users\Abhay\Desktop\todo-app\server.js:8:17 at C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\utils.js:722:9 at C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\mongo_client.js:223:23 at C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\operations\connect.js:279:21 at QueryReqWrap.callback (C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\core\uri_parser.js:56:21) at QueryReqWrap.onresolve [as oncomplete] (dns.js:202:10) [nodemon] app crashed - waiting for file changes before starting...

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 类本身.

It seems you're trying to use the static connect method of MongoClient to make a connection to your db, but you are not using the MongoClient class itself.

要连接到任何数据库,您需要一个已连接的 MongoClient 实例.使用静态连接方法,可以通过以下方式实现:

To connect to any db, you will need a connected instance of MongoClient. Using the static connect method, you can achieve it in the following way:

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 如果不传入回调函数,非常方便.使用它,您可以编写一个函数,该函数返回一个将连接实例解析到您的数据库的承诺.

However, using callbacks will be quite cumbersome. As per the docs linked above, most functions in the MongoDb driver for Node.js will return a promise if a callback function is not passed, which is very convenient. Using this, you can write a function which return a promise that resolves a connected instance to your db.

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();

这篇关于类型错误:在尝试 Mongodb Atlas Online 时无法读取未定义的属性“db"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆