简体   繁体   中英

How to close mongodb connections from node js using mongoose or mongodb client

there are approximately 21000 connections are there for mongodb which are stale connections.

i have tried "currentOp" command to list all the connections. i was unable to close from node js using mongoose.

const express = require('express');
var app = express();
const mongoose = require('mongoose'),
Admin = mongoose.mongo.Admin;
const port = 3002
mongoose.set('debug', true)
var db = mongoose.createConnection('mongodb://localhost:22222/myapp', { 
useNewUrlParser: true }, () => {
  console.log('Connection db established')
})
app.use((req, res, next) => {
    console.log(req.url + ' ' + new Date());
    next();
});
const Cat = mongoose.model('cats', { name: String });

db.on('open', function (err, data) {


    new Admin(db.db).command({ currentOp: 1, '$all': true }, (err, r) => {
        var connections = []
        console.log(err)
        console.log(r.inprog.length)
        r.inprog.forEach((conn) => {
            if (conn.client) {
                console.log(conn.client)
                connections.push({ thread: conn.threadId, connection: conn.connectionId, op: conn.opid })
            }
        })
        console.log(connections)
    })
});

app.listen(port, () => {
    console.log('Server started')
})

i have used "killOp" to kill connection but didn't work. and there is no "opid" for stale connections to kill or to identify

Your mongoose connection can be closed with

mongoose.connection.close()

Make sure to put in the correct callback however, so that your database gets saved before the connection closes.

You can read more in the docs found here .

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