I
I
ikerya2018-11-08 22:34:55
MongoDB
ikerya, 2018-11-08 22:34:55

MongoDB: active connections are piling up, what should I do?

I have a site implemented in NodeJS, MongoDB base, Mongoose plugin. Recently, the site began to fall about once a day. I recently found out that this is due to a lack of memory, which occurs due to the fact that active connections are being accumulated (db.serverStatus().connections.current). This may not be related, but I have a NodeJS script that is executed by cron every minute. It checks if there is a post model in the documents with the current date. But I close the mongoose connection there, I don't know what could be the problem. The actual contents of the file:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;

const { new_time } = require("lib/functions");
const push = require("lib/push");

const apiCallback  = require("middleware/socket/apiCallback");

const mongoose = require("lib/mongoose");

const User = require("models/User");
const Post = require("models/Post");

(async () => {
    let currentPost = await Post.findCurrent(1);

    if (currentPost) {
        await currentPost.setPublished(1);

        await apiCallback.call({
            roomName: "index",
            event   : "posts.new",
            data    : {
                post: {
                    id: currentPost._id.toString()
                }
            }
        });
        await push.sendAll({
            // ненужные данные
        });
    }

    await mongoose.connection.close();

    process.exit(0);
})();

app.js:
const path           = require("path");
const express        = require("express");
const app            = express();
const bodyParser     = require("body-parser");
const cookieParser   = require("cookie-parser");
const expressSession = require("express-session");
const MongoStore     = require("connect-mongo")(expressSession);
const conf           = require("conf");
const mongoose       = require("lib/mongoose");

const expressSessionConfig = conf.get("session");

expressSessionConfig.cookie.expires = new Date(new Date().getTime() + 60 * 60 * 24 * 30 * 1000);
expressSessionConfig.store = new MongoStore({
    mongooseConnection: mongoose.connection
});

const templateDir = path.join(__dirname, conf.get("template_dir"));

app.engine("ejs", require("ejs-locals"));
app.set("views", templateDir);
app.set("view engine", "ejs")

app.use(express.static("frontend"));
app.use(cookieParser());
app.use(expressSession(expressSessionConfig));
app.use(bodyParser.urlencoded({
    extended: true
}));

require("routes")(app);

app.listen(conf.get("app_port"));

app.io.js (socket server on socket.io):
const fs   = require("fs");
const path = require("path");
const app  = require("express")();
const bodyParser  = require("body-parser");
const apiCallback = require("middleware/socket/apiCallback");
const conf = require("conf");

const sslPath    = conf.get("sslPath");
const sslOptions = {
  key : fs.readFileSync(path.join(sslPath, "key.key")),
  cert: fs.readFileSync(path.join(sslPath, "crt.crt"))
};

const server = require("https").Server(sslOptions, app);
const io     = require("socket.io")(server);

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(conf.get("api_callback:path"), apiCallback.watch(io));

require("routes/socket")(io);

server.listen(conf.get("socket_port"));

routes/socket.js:
const { in_array } = require("lib/functions");
const loadUser     = require("middleware/socket/loadUser");

const User = require("models/User");

module.exports = io => {
    io.on("connection", async socket => {
        let query   = socket.handshake.query || {};
        let { ssid } = query;

        ssid = ssid || "";

        let user        = socket.user = await loadUser(ssid);
        let oldPageName = null;

        User.setOnline(user._id, 1);

        socket.on("setPageName", pageName => {
            if (oldPageName) socket.leave(oldPageName);

            oldPageName = pageName;
            socket.join(pageName);
        });
        socket.on("disconnect", () => {
            socket.leave(oldPageName);

            User.setOnline(user._id, 0);
        });
    });
};

Can you tell me how to properly close connections so that they do not remain in memory and load the server to such an extent that it kills the MongoDB daemon process?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Abcdefgk, 2018-11-09
@Abcdefgk

Require mongoose to this file (no fancy stuff) and write mongoose.disconnect() at the end.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question