mongodb Mongo运行时错误:连接池已关闭

bgtovc5b  于 2022-12-12  发布在  Go
关注(0)|答案(2)|浏览(454)

我看到mongoose池在插入数据之前似乎已关闭,因为在我的云集群中调用mongoose数据库时出现此错误

MongoRuntimeError: Connection pool closed

但是我一直在等待所有的电话,所以我不确定为什么会出现这个问题,也许这与我定义客户的方式有关?希望有人对此有一些提示或想法

export const storeData = async (data) =>{
    const uri = `mongodb+srv://plantmaster:${password}@cluster0.yey8l.mongodb.net/plantstore?retryWrites=true&w=majority`;
    const client = await MongoClient.connect(uri, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        serverApi: ServerApiVersion.v1
      });

        const newPLantData = { name: "Company Inc", address: "Highway 37" };
        await client.db("plantstore").collection("plantdata").insertOne(newPLantData, (err, res) =>{
            if(err) throw err;
            console.log(result)
        })
       
        await client.close();
};

我在这样的快速邮递路线上调用此函数

// store data
app.post('/store', async function (req, res) {
 await storeData(req.body);
  res.send('data was stored')
})
ijnw1ujt

ijnw1ujt1#

我也遇到了同样的错误,但我在关闭连接之前等待了1500ms来修复它。

setTimeout(() => {client.close()}, 1500)
b1zrtrql

b1zrtrql2#

尝试以下示例方法

import { MongoClient } from "mongodb";

const handler = async (req, res) => {
  if (req.method === "POST") {
    const { email } = req.body;

    if (!email || !email.includes("@")) {
      res.status(422).json({ message: "Entered email is not valid" });
      return;
    }

    const url = <your-mongo-url>
    const client = new MongoClient(url);
    await client.connect();
    
    const collection = client.db("events").collection("newsletter");

    try {
      await collection.insertOne({ email });
      return res.status(201).json({
        message: "You have successfully signed up to newsletters!",
        email,
      });
    } catch (error) {
      throw res.status(500).json({ message: "Server error occured" });
    } finally {
      client.close();
    }
  }
};

export default handler;

相关问题