【问题标题】:Getting error while connecting to mongo in aws lambda在 aws lambda 中连接到 mongo 时出错
【发布时间】:2020-07-24 15:35:54
【问题描述】:

我正在尝试使用 mongodb 连接到 mongo 数据库,但它的抛出错误无法解决。

这是我的 mongo 连接功能

const {
    MongoClient,
    ObjectId,
} = require('mongodb');


const {
    MERCURY_MONGO_DB_URL,
} = process.env;
 
const initialize_mongodb_database_connection = async () => {
    
    //
    // Create a new MongoClient
    //
    const connection = new MongoClient(MERCURY_MONGO_DB_URL, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });

    // Use connect method to connect to the Server
    connection.connect((err) => {

        if (err != null) {

            console.log(`MongoDB Connection :: Error :: ${err}`);
            process.exit(1);

        } else {

            const db = connection.db('demo');
            return db;
            global.ObjectId = ObjectId;
            console.log('MongoDB Connection :: Ready');

        }
    
    });

};

module.exports = {
    initialize_mongodb_database_connection,
};

这是我尝试使用它但出现错误的地方

var db = await initialize_mongodb_database_connection();

const data = await db.collection(`access_log_${result.student_uuid}`)
                .find(where)
                .toArray();
console.log(data)

我收到了这个Cannot read property 'collection' of undefined 的错误 实际上我在哪里收集数据access_log_1747386c-9577-4073-b818-649db0ce9d50 不知道为什么它不工作?我的数据库中有那个集合。

有人可以帮忙吗?我也在为 aws lamdba 开发这个

【问题讨论】:

    标签: javascript node.js mongodb mongodb-query


    【解决方案1】:

    错误消息表明db 对象未定义。查看 initialize_mongodb_database_connection 函数时,您没有返回由 MongoClient#connect 返回的承诺。

    const initialize_mongodb_database_connection = async () => {
        ...
    
        return connection.connect((err) => {
            ...
        });
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 2021-10-03
      • 2022-01-06
      • 2019-06-21
      • 1970-01-01
      相关资源
      最近更新 更多