[英]MongoExpiredSessionError: Cannot use a session that has ended
[英]MongoDB: Error “Cannot use a session that has ended” when inserting into a collection
今天開始使用 mongoDB 並使用示例代碼首先連接到現有數據庫,然后將新的 object 添加到我的收藏中:
//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);
如果我執行上面的代碼,我會得到:插入集合時出現錯誤“無法使用已結束的 session”我認為這是因為await client.close();
因為如果將此命令添加到我的 insertOne() 函數的回調函數中,它就可以正常工作。
但是如果命令在finally中,連接是否應該在 function run() 結束時終止? 為什么 session 在我插入 object 之前就結束了?
謝謝您的幫助!
您不是在等待插入,您的代碼直接進入 finally 在插入執行之前關閉連接
await products.insertOne(newProduct)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.