gpt4 book ai didi

javascript - 每第二次运行都会抛出 : MongoError: Topology was destroyed

转载 作者:行者123 更新时间:2023-12-02 23:53:28 26 4
gpt4 key购买 nike

我正在构建一个 REST API,但每次加载我的网站时,我都会收到 MongoError:拓扑已损坏。有人可以帮我解决这个问题吗?我感觉异步运行有问题。

const client = new MongoClient(apiconfig.mongoUrl, {
useNewUrlParser: true
});

app.get("/api/:object", (req, res) => {
mongodb(req.params["object"], async (collection: Collection) => {
if (collection !== undefined) {
let result = await collection.find().toArray();
res.send(result);
}
else {
res.sendStatus(404);
}
});
});

const mongodb = (coll: string, operation: (collection: Collection) => Promise<void>) => {
client.connect((err) => {
const db = client.db("VaorraJS");
db.collections().then((collections) => {
operation(collections.find((collection) => collection.collectionName === coll)).then(() => {
client.close();
});
}).catch((error) => {
console.log("ERROR: " + error);
});
});
}

app.listen(5000);

最佳答案

我建议使用Mongoose

您正在为每个请求创建数据库连接,这不是正确的方法

const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = '<some db>';

// Use connect method to connect to the server
let db;
MongoClient.connect(url, function (err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
db = client.db(dbName);
});


app.get("/api/:object", async(req, res) => {
const collection = db.collection(req.params["object"]);
let result = await collection.find().toArray();
res.send(result);
});

关于javascript - 每第二次运行都会抛出 : MongoError: Topology was destroyed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55537880/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com