今天开始使用MongoDB,并使用示例代码首先连接到现有数据库,然后将新对象添加到我的集合中:
//jshint esversion:6
const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
const uri =
"mongodb://localhost:27017";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db('shopDB');
const products = database.collection('products');
// Query for a movie that has the title 'Back to the Future'
const query = { id: 1 };
const product = await products.findOne(query);
console.log(product);
//insert a new products
var newProduct = {id: 5, name: 'Cat', price: 10, stock: 0};
products.insertOne(newProduct, async function(err, res){
if (err) throw err;
console.log('1 product created');
})
} finally {
await client.close();
}
}
run().catch(console.dir);
如果我执行上面的代码,我会得到:**插入到集合中时出现错误“Cannot Use a Session That That End”**我认为这是因为await client.close();
,因为如果将此命令添加到我的intertOne()函数的回调函数中,它工作得很好。
但是,如果命令在Finally中,那么连接不应该在函数run()结束时终止吗?为什么在我可以插入对象之前会话就结束了?
谢谢你的帮助!
1条答案
按热度按时间bvpmtnay1#
您不是在等待插入,而是您的代码直接转到最后,在插入执行之前关闭连接