Hello Zeeshan, Thanks for your code snippet. I took yours as a reference and I ended up changing it accordingly which suits for typescript. I made it very simple for now to work and that is why I haven't added the types fully.
The below code block works fine, except the commented one. All 'this' inside the functions are throwing error and would be great if you help me where I am doing wrong.
importmongoosefrom"mongoose";importloggerfrom"./logger";constmakeNewConnection=(uri:string):mongoose.Connection=>{letconn:mongoose.Connection=mongoose.createConnection(uri,{useNewUrlParser:true,useUnifiedTopology:true,useCreateIndex:true,});/* conn.on("error", function (error) {
logger.info(`MongoDB :: connection ${this.name} ${JSON.stringify(error)}`);
conn
.close()
.catch(() =>
logger.warn(`MongoDB :: failed to close connection ${this.name}`)
);
});
conn.on("connected", function () {
mongoose.set("debug", function (col, method, query, doc) {
logger.debug(
`MongoDB :: ${this.conn.name} ${col}.${method}(${JSON.stringify(
query
)},${JSON.stringify(doc)})`
);
});
logger.info(`MongoDB :: connected ${this.name}`);
});
conn.on("disconnected", function () {
logger.info(`MongoDB :: disconnected ${this.name}`);
}); */returnconn;};constdbOne=makeNewConnection(process.env.DB_ONE);constdbTwo=makeNewConnection(process.env.DB_TWO);export{dbOne,dbTwo};
It's quite old question, but this may help someone in the future: check if your process.env variables aren't undefined. To fix this, you can move dotenv.config(); to connections.js file and use in before makeNewConnection(...) function.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
@vigneshncc can you share your source code
Hello Zeeshan, Thanks for your code snippet. I took yours as a reference and I ended up changing it accordingly which suits for typescript. I made it very simple for now to work and that is why I haven't added the types fully.
The below code block works fine, except the commented one. All 'this' inside the functions are throwing error and would be great if you help me where I am doing wrong.
It's quite old question, but this may help someone in the future: check if your
process.env
variables aren'tundefined
. To fix this, you can movedotenv.config();
toconnections.js
file and use in beforemakeNewConnection(...)
function.