javascript - 如何正确执行对 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
}
解决方案
推荐阅读
- amazon-web-services - AWS CloudFormation:如何在 AWS Pipeline 中使用 Github Enterprise 作为源
- javascript - 如何减少重复来源?
- c++ - 使用 thread::detach 时如何检查线程是否已完成
- go - Go protobuf 中单独消息和服务定义的最佳实践?
- reactjs - 如何在等待的非异步中调用异步方法?
- java - JpaRepository findBy 查询 (SELECT) 正在更新数据库中的记录
- nexmo - 在 Nexmo 中获取呼出电话的实时音频流
- html - 父 div 在其元素之前变小
- amazon-web-services - EC2:在我自己创建的 VPC 中启动公共 EC2 时出现此错误
- c# - 不改变 JSON 的 JSON 数组的 NewtonSoft 继承反序列化