每秒钟运行一次:MongoError:拓扑已被破坏

时间:2019-04-05 14:40:17

标签: javascript node.js mongodb typescript express

我正在构建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);

1 个答案:

答案 0 :(得分:1)

我建议使用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);
});