简体   繁体   中英

I want to know about mongodb

I'm currently creating an API server that reads and writes. Using MongoDB

The library uses Mongoose.

I wonder if db.close() must be used when reading and writing.

datamodel.js:

var db = mongoose.connect('mongodb://localhost/testdb', {useNewUrlParser: true,useUnifiedTopology:true});
mongoose.Promise = global.Promise;

.....
Boards = mongoose.model("boards", BoardSchema);
exports.Boards = Boards;

routes/getList.js:

let result = await Boards.find().sort({"date": -1});

Should I close the DB declared above with db.close() when reading or writing?

(Very generic answer, but should help you get started with what to research)

Closing MongoDB connection depends on how is the connection established in the first place.

  1. Are you initialising the connection on server startup: If yes, you should not close the connection. ( But initialising the connection on server startup is bad idea because, if connection is lost to server (like database server restart), then you would also have to restart the application or set reconnectTries )

  2. Are you using connection pool : If you are using connection pool, then closing and opening of connections is taken care by Mongoose itself. All you have to do is, release the connection after use, so that, it's available for other requests.

  3. Are you creating connection per request: If yes, then you should close the connection before returning the response or you would quickly run out of available connections at database server.

you can call mongoose.disconnect() to close the connection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM