Mongoose每次的连接状态0

bvjveswy  于 2023-01-02  发布在  Go
关注(0)|答案(1)|浏览(136)

我正在使用nodejs和mongoose连接到我的MongoDB数据库。我尝试检查连接状态,如果它已连接或未连接。我使用mongoose.connection.readyState。
连接工作正常(MongoDB Cloud Atlas &我的本地安装),但终端每次都显示状态0(断开)。
这是我的密码:'

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();

'
也许有人可以给我一个提示,我找了,但没有找到我的错误。
我搜索和阅读了文档,但我不能解决我的问题。也许有人可以给我一个提示,我认为这是一个小问题。

hgqdbh6s

hgqdbh6s1#

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();

相关问题