Reputation: 748
I have a node.js script that I want to run periodically that writes to mongodb using mongoose. It connects to mongodb, writes, and disconnects. The problem is that the script seems to hang sometimes. I have to manually terminate the script (ctrl+C).
mongoose.connect(MONGODB_URL);
var db = mongoose.connection;
db.on('error', function(err) {
console.log(err);
});
db.on('open', function() {
console.log('opened');
});
db.on('close', function() {
console.log('closed');
});
Model.update(....., function(err) {
if (err) throw err;
mongoose.disconnect();
});
Everything seems to be fine. The script prints opened
and closed
and updates the database correctly, but doesn't terminate after that. I also disconnect inside the callout after all updates to the database are done so there shouldn't be any pending queries that would prevent the script from terminating.
A similar question was asked here: Properly close mongoose's connection once you're done But it doesn't look like there were any true solutions.
EDIT:
I can get it to terminate by adding process.exit()
at the end, but that shouldn't be the case.
Upvotes: 1
Views: 1649
Reputation: 996
Here's a sample script for accessing a Mongo database:
const { Model } = require("../models");
const mongoose = require("mongoose");
async function run() {
let c = `mongodb://${process.env.DBUSER}`;
c += `:${process.env.DBPASS}`;
c += `@${process.env.DBHOST}`;
c += `:${process.env.DBPORT}`;
c += `/${process.env.DBNAME}`;
await mongoose.connect(
c,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {}
);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB connection error:"));
const instances = await Model.find({});
for (const i of instances) {
console.log(i.title);
}
mongoose.connection.close();
}
run().catch((error) => console.log(error.stack));
If this is saved in a file like script.js, just run node script.js
.
Upvotes: 0
Reputation: 3333
mongoose.connection.close()
works for me but you need to make sure all your db operations have completed before calling it.
Upvotes: 2