'type conversion error while executing mongoDB find

I am following official MongoDB typescript tutorial to convert my javascript app to typescript one. After code conversion i am facing following error:

routes/users.router.ts:15:19 - error TS2352: Conversion of type 'WithId<Document>[]' to type 'User[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
    Type 'WithId<Document>' is missing the following properties from type 'User': email, hash

15     const users = (await collections.users.find({}).toArray()) as User[];
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

routes/users.router.ts:

// External Dependencies
import express, { Request, Response } from "express";
import { ObjectId } from "mongodb";
import { collections } from "../services/database.service";
import User from "../models/user";

// Global Config
export const usersRouter = express.Router();

usersRouter.use(express.json());

// GET
usersRouter.get("/", async (_req: Request, res: Response) => {
    try {
        const users = (await collections.users.find({}).toArray()) as User[];

        res.status(200).send(users);
    } catch (error: any) {
        res.status(500).send(error.message);
    }
});

models/user.ts:

// External dependencies
import { ObjectId } from "mongodb";

// Class Implementation
export default class User {
    constructor(
        public email: string,
        public hash: string,
        public id?: ObjectId
    ) {}
}

services/database.service.ts:

import "dotenv/config";

// External Dependencies
import * as mongoDB from "mongodb";

// Global Variables
export const collections: { users?: mongoDB.Collection } = {};

// Initialize Connection
export async function connectToDatabase() {
    const client: mongoDB.MongoClient = new mongoDB.MongoClient(
        process.env.DB_CONN_STRING || ""
    );

    await client.connect();

    const db: mongoDB.Db = client.db(process.env.DB_NAME);

    const usersCollection: mongoDB.Collection = db.collection(
        process.env.USERS_COLLECTION_NAME || ""
    );

    collections.users = usersCollection;

    console.log(
        `Successfully connected to database: ${db.databaseName} and collection: ${usersCollection.collectionName}`
    );
}

index.ts:

import "dotenv/config";
import express, { Express } from "express";
import { connectToDatabase } from "./services/database.service";
import { usersRouter } from "./routes/users.router";
import cors from "cors";

const app: Express = express();

app.use(cors());

connectToDatabase()
    .then(() => {
        app.use("/users", usersRouter);

        app.listen(process.env.SERVER_PORT, () => {
            console.log(
                `⚡️[server]: Server is running at https://${process.env.SERVER_DOMAIN}`
            );
        });
    })
    .catch((error: Error) => {
        console.error("Database connection failed", error);
        process.exit();
    });

What changes are needed to the code from tutorial to fix it and avoid compile errors?



Sources

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

Source: Stack Overflow

Solution Source