TypeError:尝试访问Mongodb Atlas在线时无法读取未定义的属性“ db”

时间:2020-07-11 06:58:54

标签: javascript node.js mongodb crud mongodb-atlas

[nodemon]从node server.js开始 C:\ Users \ Abhay \ Desktop \ todo-app \ node_modules \ mongodb \ lib \ utils.js:725 抛出错误; ^

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 [完成时](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)
})

1 个答案:

答案 0 :(得分:1)

似乎您正在尝试使用static connect method中的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,这非常方便。使用此功能,您可以编写一个函数,该函数返回一个可将连接实例解析为数据库的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();