There is a simple nestJS service, which returns the result of a mongoDb query. As you can see, I tried to set the expected result type, which is an array of documents.
class MyDataset {
group: string
location: string
type: string
reported: Date
}
async getDatasets(): Promise<Array<MyDataset>> {
const Collection = this.db.collection('collection')
const result = await Collection.find({}).toArray()
return result // <-- ts error
}
But I do get the TS error
Type 'Document[]' is not assignable to type 'MyDataset[]'.
Type 'Document' is missing the following properties from type 'MyDataset': group, location, type, reported
I don't see, what I am doing wrong. Could somebody explain the problem?
CodePudding user response:
The error implies a mismatch between the type you're expecting MyDataset
and the one Collection.find({}).toArray()
is returning. The mongo db documentation states the toArray() methods returns an array of Documents.
This replicates the same behaviour:
type DocumentA = {
group: string
location: string
type: string
reported: Date
}
type DocumentB = {
anotherField: string
}
const arrayOfDocumentsA = () => {
const res: DocumentA[] = [];
return res;
}
const arrayOfDocumentsB = () => {
const res: DocumentB[] = [];
return res;
}
const getDatasets = (): Array<DocumentA> => {
return arrayOfDocumentsB(); // ts error
};
This will error out with the following error:
Type 'DocumentB[]' is not assignable to type 'DocumentA[]'.
Type 'DocumentB' is missing the following properties from type 'DocumentA': group, location, type, reported ts(2322)