node.jsmongodbtypescripttypescript-typingsconnect-mongo

TypeScript - Argument of type '{}' is not assignable to parameter of type '{}' - MongoStore


I'm relatively new to TS and I've have encountered a type problem in new MongoStore() parameters. Typically I can reuse the Native MongoDB connection by writing db: database as an argument in JS, but TS shows the following error:

Argument of type '{ db: Db; }' is not assignable to parameter of type 'MongoUrlOptions | MogooseConnectionOptions | NativeMongoOptions | NativeMongoPromiseOptions'. Type '{ db: Db; }' is not assignable to type 'NativeMongoPromiseOptions'. Property 'dbPromise' is missing in type '{ db: Db; }'.

I've tried writting new MongoStore({ db: database } as NativeMongoOptions), but this doesn't help either.

[UPDATE] adding as NativeMongoOptions produces a diff error:

Type '{ db: Db; }' is not assignable to type 'NativeMongoOptions'. Types of property 'db' are incompatible. Type 'import("/node_modules/@types/mongodb/index").Db' is not assignable to type 'import("/node_modules/@types/connect-mongo/node_modul...'. Property 'authenticate' is missing in type 'Db'.

Is this a problem of my code or the TS typings?

Here below is the fragment of my code.

const MongoStore: connectMongo.MongoStoreFactory = connectMongo(session);
const app: express.Application = express();

enableMiddleware(app);

(async () => {
    try {
        const client: mongodb.MongoClient = await mongodb.MongoClient.connect(config.dbUrl, { useNewUrlParser: true });
        console.log("Connected correctly to server");
        const database: mongodb.Db = client.db(config.dbName);

        app.use(session({
            resave: false,
            saveUninitialized: false,
            secret: "secret123",
            store: new MongoStore({
                db: database,
            }),
        }));

        app.use(router(database));
    } catch (error) {
        console.log("Error connecting to MongoDB", error);
    }
})();

Solution

  • Found out the problem, it was with the TS typings all along, the @types/connect-mongo uses an older version of @types/mongodb ^2, where I am using @types/mongodb ^3 in my project.

    Current solution, update the @types/connect-mongo package dependencies to the newest (overwriting @types/mongodb ^2 to ^3).