本文介绍了每秒运行一次:MongoError:拓扑被破坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a REST API but every second time I load my site I get a MongoError: Topology was destroyed. Can someone help me fixing this? I have a feeling that there is something wrong with the asynchronous running.

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

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

you are creating DB connection for every request, which is not the correct way

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);
});

这篇关于每秒运行一次:MongoError:拓扑被破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 03:28