I am trying to connect to Mongodb to define connect, disconnect and use it in an API. I receive this TypeError of cannot read properties of undefined (reading '0). I console to check if the array containing all connections associated with this Mongoose instance but had only 0 instead of list of connections. Below is the Code Snippet.
import mongoose from 'mongoose';
const connection = {};
async function connect() {
if (connection.isConnected) {
console.log('already connected');
}
if (mongoose.connections.length > 0) {
connection.isConnected = mongoose.connections[0].readyState;
console.log('cone', connection.isConnected);
if (connection.isConnected === 1) {
console.log('use previous connection');
return;
}
await mongoose.disconnect();
}
const dbConnect = mongoose.connect(process.env.MONGODB_URI, {
// useNewUrlParser: true,
useUnifiedTopology: true,
// useCreateIndex: true,
});
console.log('new connection');
connection.isConnected = dbConnect.connections[0].readyState;
}
async function disconnect() {
if (connection.isConnected) {
if (process.env.NODE_ENV === 'production') {
await mongoose.disconnect();
connection.isConnected = false;
} else {
console.log('not disconnected');
}
}
}
const db = { connect, disconnect };
export default db;
The Error I get is this
error - (api)\utils\db.js (25:49) @ Object.connect
TypeError: Cannot read properties of undefined (reading '0')
23 | });
24 | console.log('new connection');
> 25 | connection.isConnected = dbConnect.connections[0].readyState;
| ^
26 | console.log("cone1", connection.isConnected);
27 | }
CodePudding user response:
There were no types on the mongoose.connect() as connections. So just needed to remove the connections[0].readyState I was looking for.
import mongoose from 'mongoose';
const connection = {};
async function connect() {
if (connection.isConnected) {
console.log('already connected');
return;
}
if (mongoose.connections.length > 0) {
connection.isConnected = mongoose.connections[0].readyState;
if (connection.isConnected === 1) {
console.log('use previous connection');
return;
}
await mongoose.disconnect();
}
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
};
const uri = process.env.MONGODB_URI;
const db = mongoose.connect(uri, options);
console.log('new connection');
connection.isConnected = db
if (!uri) {
throw new Error('Add your Mongo URI to .env');
}
}
async function disconnect() {
if (connection.isConnected) {
if (process.env.NODE_ENV === 'production') {
await mongoose.disconnect();
connection.isConnected = false;
} else {
console.log('not disconnected');
}
}
}
const db_export = { connect, disconnect };
export default db_export;