[英]How to close mongodb connection using mongoose
嗨,誰能告訴我使用 mongoose 關閉 mongodb 連接的正確方法。我嘗試檢查了很多資源,但找不到我要找的東西。 我不明白什么時候關閉它。 誰能給出完整的例子。
是這樣的嗎?
const mongoose = require("mongoose");
module.exports = () => {
mongoose.connect(process.env.MONGODB_URI);
mongoose.connection.on("error", (err) => {
console.log(err, "ERROR");
process.exit(1);
});
// disconnect here?
mongoose.disconnect()
};
還是在每次查詢后都這樣關閉?
const mongoose = require("mongoose");
static async getBestSellingProducts(cb) {
try {
let results = await ProductModel.find(
{
stock: { $gte: 1 },
sold: { $gt: 0 },
},
"dbId name photoURL sold",
{
sort: { sold: -1 },
limit: 9,
}
).exec();
cb(null, results);
// disocnnect here?
mongoose.disconnect();
} catch (err) {
cb(err, null);
// disconnect here
mongoose.disconnect();
}
}
如果您希望您的程序之后執行任何請求,則不應在每次請求后關閉連接。 當您的程序停止時關閉它確實有意義,即使您在技術上不必這樣做。
process.on('exit', function (){
mongoose.disconnect();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.