提问者:小点点

如何用try catch将常用mongodb查询改为异步


这是我使用express js的查询代码,这个查询工作,但我认为使用异步比这个更可靠

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"

const client = new MongoClient(url, { useUnifiedTopology: true });

app.get("/", async (req, res) => {
    // this is myquery code with right result 
 
    client.connect((err) => {
        assert.equal(null, err);
        const db = client.db(db_n)
        db.collection("list").find({}).toArray((err, result) => {
            if(err) throw res.send({ status: "Error when react data", bool: false}).status(450);
            res.send(result).status(200);
        })
    })    

});

共2个答案

匿名用户

尝试一下这个,与您的不完全相同,但将使您了解如何在Try/catch中使用async/await

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"

const client = new MongoClient(url, { useUnifiedTopology: true });

app.get('/', async (req, res) => {
    
    // Connect client if it's not connected
    if(!client.isConnected()) {
        await client.connect();

        // you can also catch connection error
        try {
            await client.connect();
        catch(err) {
            return res.status(500).send();
        }
    }

    const db = client.db(db_n);

    try {
        // Run queries
        const result = db.collection("list").find({});
        res.json(await result.toArray());
    } catch (err) {
        // Catch any error
        console.log(err.message);
        res.status(450).send();
    }
});

匿名用户

我没有对此进行测试,但可以尝试以下内容:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"

let client;

const getDb = async () => {
  // If we don't have a client, create one.
  if (!client) client = new MongoClient(url, { useUnifiedTopology: true });
  // If we are not connected, then connect.
  if (!client.connected()) await client.connect();
  // Get our database
  return client.db(db_n);
}

app.get("/", async (req, res) => {
try {
  const db = await getDb();
  const results = await db.collection("list").find({});
  results.forEach((err, result) => {
    if(err) throw new Error();
    res.send(result).status(200);
  })
});
} catch (err) {
  res.send({ status: "Error when react data", bool: false}).status(450);
}

我觉得奇怪的是,你循环遍历结果,并且只返回第一个结果。

相关问题