Home > front end >  Mongoose connection state everytime 0
Mongoose connection state everytime 0

Time:01-02

i'm using nodejs and mongoose to connect to my MongoDB Database. I try to check the connection state, if its connected or not. I use mongoose.connection.readyState for this.

The connection works fine (MongoDB Cloud Atlas & my local installation) but the terminal shows me state 0 (disconnected) everytime.

This is my Code: `

const { mongoose } = require('mongoose');

const uriAtlas = "mongodb srv://<Username>:<Password>@MyClusterAtlas.net/";
const urilocal = "mongodb://127.0.0.1:27017/";

const status = mongoose.connection.readyState;

// Define Delay
const delay = ms => new Promise(res => setTimeout(res, ms));

async function createConnection() {
    mongoose.set('strictQuery', true);
    await mongoose.connect(urilocal,
    // Check Connection state after 5Seconds.
    
    await delay(5000));
    

    // Show connection state
    if (status == 1) {
        console.log("Connected")
    } else {
        console.log("Not Connected!"),
        console.log(`Connection state is: ${status}`);
    }
    };

createConnection();

`

Maybe someone can give me a hint, i searched but doesn't find my error.

I searched and read the documentation but i cant solve my problem. Maybe someone can give me a hint, i think its a little issue.

CodePudding user response:

const { mongoose } = require('mongoose');

const uriAtlas = "mongodb srv://<Username>:<Password>@MyClusterAtlas.net/";
const urilocal = "mongodb://127.0.0.1:27017/";

// Define Delay
const delay = ms => new Promise(res => setTimeout(res, ms));

async function createConnection() {
    mongoose.set('strictQuery', true);
    await mongoose.connect(urilocal,
    // Check Connection state after 5Seconds.
    
    await delay(5000));
    
    const status = mongoose.connection.readyState;

    // Show connection state
    if (status == 1) {
        console.log("Connected")
    } else {
        console.log("Not Connected!"),
        console.log(`Connection state is: ${status}`);
    }
};

createConnection();
  • Related