'Property Type Does Not Exist - MongoDB WithId<Document>
Using:
- ts-node: 10.7.0
- MongoDB: 4.4.1
- GraphQL: 16.3
I am trying to get a response back from a mongo db request.
The request is successfully coming back, but typescript is throwing errors related to properties not existing on the type. I have declared the interface.
The error I am getting is (on 3rd console log in code below):
Property 'schema' does not exist on type 'WithId<Document>[]'
Code:
interface permissionSchemaCollectionResponse extends WithId<Document> {
_id: ObjectId;
collection: string;
schema: any;
}
const permissionSchemaCollectionResponse = (await
permissionSchemaCollection.find(filter).toArray());
console.log('permissionSchemaCollectionResponse');
console.log(permissionSchemaCollectionResponse);
console.log(permissionSchemaCollectionResponse.schema.record);
Response from Mongo:
permissionSchemaCollectionResponse
[
{
_id: new ObjectId("62093b950759ba6867f477e2"),
collection: 'apps',
schema: { record: [Object], properties: [Object] }
}
]
Attempt at adding a "model":
permissions.ts
import type { WithId, Document, ObjectId } from 'mongodb'
export default class PermissionSchema {
constructor(public id: ObjectId, public collection: string, public schema: any) {}
}
Response using "as" imported model:
const permissionSchemaCollectionResponse = (await permissionSchemaCollection.find(filter).toArray()) as PermissionSchema[];
Error when using imported model
Conversion of type 'WithId<Document>[]' to type 'PermissionSchema[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Solution 1:[1]
Ended up being both a typing and trying to access a array as an attribute errors.
Resolved with:
model:
import type { WithId, Document, ObjectId } from 'mongodb'
export default class Permissions {
constructor(public _id: ObjectId, public collection: string, public schema: any) {}
}
Import model with:
import Permissions from "../../models/permissions";
Getting and typing response from mongo:
const permissionSchemaCollectionResponse: Permissions[] = (await permissionSchemaCollection.find(filter).toArray()) as Permissions[];
console.log('permissionSchemaCollectionResponse');
console.log(permissionSchemaCollectionResponse);
console.log(permissionSchemaCollectionResponse[0].schema);
Solution 2:[2]
Pass the schema type as a generic to the find method:
const permissions = await permissionSchemaCollection.find<PermissionSchema>(filter).toArray()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | S.B. |
Solution 2 | Vb Streetz |