MongoDB:插入到集合中时出现错误“无法使用已结束的会话”

hts6caw3  于 2022-10-04  发布在  Go
关注(0)|答案(1)|浏览(117)

今天开始使用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()结束时终止吗?为什么在我可以插入对象之前会话就结束了?

谢谢你的帮助!

bvpmtnay

bvpmtnay1#

您不是在等待插入,而是您的代码直接转到最后,在插入执行之前关闭连接

await products.insertOne(newProduct)

相关问题