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.
2
Answers
Ended up being both a typing and trying to access a array as an attribute errors.
Resolved with:
model:
Import model with:
Getting and typing response from mongo:
Pass the schema type as a generic to the find method: