On the second failure of using mongodb in express

-problem description

recently learned to use express and mongodb;
to do demo examples, and found a problem, that is, every time a request is sent from the page to add data to the table, the first time is normal, the second time it is wrong?

-corresponding code

  • express version 4.16.4
  • mongodb version 3.1.10
// express
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
// mongodb
const urlDB = "mongodb://localhost:27017"
const MongoClient = require("mongodb").MongoClient
const Client = new MongoClient(urlDB, { useNewUrlParser: true })
// mongodb function
const insertDoc = function(db, collectionName, data, callback) {
  const collection = db.collection(collectionName)
  collection.insertOne(data, (err, res) => {
    callback && callback(err, res)
  })
}

app.use(bodyParser.urlencoded({ extended: true }))
// 
app.use("/static", express.static("public"))
// 
app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html")
})
// 
app.post("/insert", (req, res) => {
  // mongodb
  Client.connect((err) => {
    const db_ = Client.db("user")
    console.log("--", err);
    insertDoc(db_, "user", req.body, (errDB, resDB) => {
      if (errDB) {
        console.log("--", errDB);
        res.send({succ: false})
      } else {
        resDB.result.ok && res.send({succ: true})
        Client.close()
      }
    })
  })
})
// 
app.listen(3000)

-error code

the options [servers] is not supported
the options [caseTranslate] is not supported
-- null
-- { MongoError: server instance pool was destroyed
    at basicWriteValidations (/Users/chisecj/Documents/project/study/test_node/09_express/node_modules/_mongodb-core@3.1.9@mongodb-core/lib/topologies/server.js:700:41)
    at Server.insert (/Users/chisecj/Documents/project/study/test_node/09_express/node_modules/_mongodb-core@3.1.9@mongodb-core/lib/topologies/server.js:805:16)
    at Server.insert (/Users/chisecj/Documents/project/study/test_node/09_express/node_modules/_mongodb@3.1.10@mongodb/lib/topologies/topology_base.js:321:25)
    at insertDocuments (/Users/chisecj/Documents/project/study/test_node/09_express/node_modules/_mongodb@3.1.10@mongodb/lib/operations/collection_ops.js:838:19)
    at insertOne (/Users/chisecj/Documents/project/study/test_node/09_express/node_modules/_mongodb@3.1.10@mongodb/lib/operations/collection_ops.js:868:3)
    at executeOperation (/Users/chisecj/Documents/project/study/test_node/09_express/node_modules/_mongodb@3.1.10@mongodb/lib/utils.js:420:24)
    at Collection.insertOne (/Users/chisecj/Documents/project/study/test_node/09_express/node_modules/_mongodb@3.1.10@mongodb/lib/collection.js:464:10)
    at insertDoc (/Users/chisecj/Documents/project/study/test_node/09_express/app.js:12:14)
    at Client.connect (/Users/chisecj/Documents/project/study/test_node/09_express/app.js:30:5)
    at result (/Users/chisecj/Documents/project/study/test_node/09_express/node_modules/_mongodb@3.1.10@mongodb/lib/utils.js:414:17) name: "MongoError", [Symbol(mongoErrorContextSymbol)]: {} }
Apr.08,2022

Client.close ()
you have turned off client, of course you made a mistake the second time. Just get rid of it.
MongoClient object should remain singleton throughout its life cycle, and should not be closed or closed before exiting the application, because it also maintains connection pooling. Once closed and opened next time, the connection needs to be rebuilt, which is a waste of resources and reduces efficiency. So the way you write it below is also wrong.


after re-reading the document and sorting out the logic, I found that there was a mistake in my usage and understanding!

  • according to the official instance, you should create a new instance for each connection, not just one;
  • as mentioned in answer 1, I turned off the only instance, so I had to report it wrong;
  • so you should just move the new MongoClient into the route;
app.post('/insert', (req, res) => {
  // mongodb
  const Client = new MongoClient(DBurl, { useNewUrlParser: true })
  Client.connect((err) => {
    const db_ = Client.db('user')
    console.log('--', err);
    insertDoc(db_, 'user', req.body, (errDB, resDB) => {
      if (errDB) {
        console.log('--', errDB);
        res.send({succ: false})
      } else {
        resDB.result.ok && res.send({succ: true})
        Client.close()
      }
    })
  })
})
  • or use
instead of creating a new instance.
app.post('/insert', (req, res) => {
  // mongodb
  MongoClient.connect(DBurl, { useNewUrlParser: true }, (err, client) => {
    // console.log('client--', client);
    const db_ = client.db('user')
    console.log('--', err);
    insertDoc(db_, 'user', req.body, (errDB, resDB) => {
      if (errDB) {
        console.log('--', errDB);
        res.send({succ: false})
      } else {
        resDB.result.ok && res.send({succ: true})
        client.close()
      }
    })
  })
})
Menu