首页 > 解决方案 > 如何正确执行对 MongoDB 客户端连接的查询

问题描述

当尝试在 Node.JS 中对 MongoDB 数据库执行查询(insertOne)时,出现错误:

/* *Note that the connect to [object Object] is me logging that the connection is created*/

Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
Connected to [object Object]
(node:58480) UnhandledPromiseRejectionWarning: MongoError: Cannot use a session that has ended

我有一个创建连接并接受回调函数的函数。连接创建后,回调函数被调用。我应该执行的回调接收一个集合和一个要插入到集合中的文档。我已经验证了集合和文档变量是正确的。似乎连接功能实际上正在连接,但我收到错误:

(node:58480) UnhandledPromiseRejectionWarning: MongoError: Cannot use a session that has ended

我从mongodb文档中看到insertOne方法需要使用await;但是,在使用它时,我收到一条错误消息,指出 cannot use it with a function that is not asynchronous。由于某种原因,下面的逻辑不起作用。根本没有将记录插入数据库,但它似乎确实创建了连接(由这一行记录 console.log( `Connected to ${ state.db }` );:)

这是我的逻辑:

const { MongoClient, ObjectID } = require('mongodb');
// Environment Config
const env = process.env.NODE_ENV || 'development';
const config = require( '../config' )[ env ];
const dbConfig = config.database;

const state = {
    db: null
};

const getPrimaryKey = _id => ObjectID( _id );
const getDB = () => state.db;

const getConnectionString = () => {
    const protocol = dbConfig.protocol;
    const host = dbConfig.host;
    const port = dbConfig.port;
    return `${ protocol }://${ host }:${ port }`;
};



async function connect( callback ){
    if( getDB() ){
        callback();
    } else {
        const connectionString = getConnectionString();
        const client = new MongoClient(
            connectionString, dbConfig.options
        );

        try {
            await client.connect();
            state.db = client.db( dbConfig.db );
            console.log( `Connected to ${ state.db }` );
            callback();
        } catch ( exception ) {
            console.error( exception );
        } finally {
            client.close();
        }
    }
};


function insertDocument( collectionName, document ){
    function callback(){
        const db = getDB();
        const commandText = `${ db }.${ collectionName }.insertOne(${ document })`;
        const dbCollection = db.collection( collectionName );
        //const result = await dbCollection.insertOne( document ); //results in await is only valid in async funciton
        const result = dbCollection.insertOne( document );
        const resultText = `${ result.insertedCount } documents were inserted with the _id: ${ result.insertedId }`;
        const returnText = `Command: ${ commandText }; Result: ${ resultText }`;
        return returnText;
    }
    
    connect( callback );
}



module.exports = {
    getDB
    ,connect
    ,getPrimaryKey
    ,insertDocument
}

标签: javascriptnode.jsmongodbasync-await

解决方案


推荐阅读