Schema operations in routes proceed without a hitch. But when I reuse the same code (just a find() call for example) and execute it in a file ('node test.js'), I get - "MongooseError: Operation refreshtokens.findOne() buffering timed out after 10000ms."
So I tried checking mongoose.connection.readyState and sure enough it equals 0 (disconnected). Why? When again, mongoose.connection is never touched in my routes and I've never had any issues there (it's only initialized in server.js).
Ultimately I'm trying to create an executable that I'll schedule, and it will need to access the database.
Nothing unusual about the code (I don't think ;) -
server.js
const express = require('express')
const app = express()
const mongoose = require('mongoose')
mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true, useUnifiedTopology: true})
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('Connected to Database'))
...
./models/refreshtoken.js
const mongoose = require('mongoose')
const refreshTokenSchema = new mongoose.Schema({
token: {
type: String,
required: true
}
})
module.exports = mongoose.model('RefreshToken', refreshTokenSchema)
Test executable (test.js)
const RefreshToken = require('./models/refreshtoken.js');
const mongoose = require('mongoose');
(async () => {
await testGetToken();
console.log("ran testGetToken()");
})().catch(e => {
// Deal with the fact the chain failed
console.log(e)
});
async function testGetToken() {
try {
console.log("here in testGetToken() call")
console.log("pre if mongoose.connection = " + mongoose.connection.readyState);
if (mongoose.connection.readyState != 1) {
await mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true, useUnifiedTopology: true})
}
console.log("post if mongoose.connection = " + mongoose.connection.readyState);
const token = await RefreshToken.find()
console.log(token)
} catch (err) {
console.log("testGetToken() err = " + err)
}
}
The executable will get and print the token after I added in the if statement with await mongoose.connect but then the process doesn't close out (I have to ctrl-c twice). Why? (And as noted at top, without the await mongoose.connect, I get the MongooseError.)
Best thing to know is why does mongoose have a mind of its own and is disconnecting only in files I execute (and how to correct it). Added mongoose.connection.on('disconnected'...) event code in server.js too and it never trips.
Next best thing would be if we didn't expect any deleterious effects in proceeding as such, how to get the executable's process to close out. I can do more homework here but I tend to think it's best to resolve problems rather than ignore them (see: Best thing)? :)
Appreciate any help you can offer. Thank you.