'Mongoose connection does not contain models and collections

I have a problem with my Mongoose connections and i don't understand how I can fix it because it looks like it happens randomly

I have a Serverless API that I run offline. I use "serverless-middleware-plugin" to connect and disconnect from my DB

My connect middleware looks like that :

export const handler = async (event, context) => {
    try {
        if(mongoose.connections[0].readyState == 1) return Promise.resolve();
        return await mongoose.connect(
            mongoURI,{ 
                useCreateIndex: true,
                useNewUrlParser: true, 
                useUnifiedTopology: true,  
                useFindAndModify: false
            }
        )
    } catch (error) {
        context.end();
        return response({
            statusCode: 500,
            body: error.toString()
        });
    }   
};

And my response middle (which disconnect mongoose after the execution of my function) looks like that :

export const handler = async (event, context) => {
    if(mongoose.connections[0].readyState == 1)  await mongoose.disconnect()
    const { statusCode, body } = context.prev;
    return response({
        statusCode: (statusCode || 500) ? statusCode : 500,
        body: statusCode? body: context.prev.toString()
    });
};

If I log my mongoose.connections[0] after the mongoose.connect() in my connect middleware, it should contains models and collections of my DB base, like that :

   models: {
     Account: Model { Account },
     Announces: Model { Announces }
   },
   modelSchemas: {
     Account: [Schema],
     Announces: [Schema]
   },
   collections: {
    Account: NativeCollection {
     collection: [Collection],
     Promise: [Function: Promise],
     modelName: 'Account',,
     name: 'Account',
     collectionName: 'Account',
    },
    Announces: NativeCollection {
     collection: [Collection],
     Promise: [Function: Promise],
     modelName: 'Announces',
     name: 'Announces',
     collectionName: 'Announces'
   }
}

But rarely, it does not contains anything in models or collections object, but the connection readyState is indeed equal to 1. And it result in a timeout request like Operation `Account.find()` buffering timed out after 10000ms

If you have any ideas why this is happening, I'm all ears

If you need more informations about my API, Serverless configuration, or schemas configurations, don't hesitate to ask

Thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source