简体   繁体   中英

Mongodb/Mongoose types aggregation incompatibility

After migrating nodejs server to a newer version of mongoose, I encountered a weird typescript error referring to $sort aggregation.

My versions

dependencies "mongoose": "^6.2.10",

Dev dependencies "@types/mongoose": "^5.11.97", "typescript": "^4.6.3"

I simplify code.

export const timetableTest = (group: string): Promise<IGroupTimetableEvents[]> => {
    const agg = [{ $match: { group } }, { $sort: { reference: 1 } }];
    const result = GroupEvent.aggregate(agg).exec();
    return result;
};

GroupEvent.aggregate(agg) does not accept agg variable, I see the following message.

Argument of type '({ $match: { group: string; }; $sort?: undefined; } | { $sort: { reference: number; }; $match?: undefined; })[]' is not assignable to parameter of type 'PipelineStage[]'. Type '{ $match: { group: string; }; $sort?: undefined; } | { $sort: { reference: number; }; $match?: undefined; }' is not assignable to type 'PipelineStage'. Type '{ $sort: { reference: number; }; $match?: undefined; }' is not assignable to type 'PipelineStage'. Type '{ $sort: { reference: number; }; $match?: undefined; }' is not assignable to type 'Sort'. Types of property '$sort' are incompatible. Type '{ reference: number; }' is not assignable to type 'Record<string, 1 | -1 | { $meta: "textScore"; }>'. Property 'reference' is incompatible with index signature. Type 'number' is not assignable to type '1 | -1 | { $meta: "textScore"; }'.ts(2345)

I see the issue is coming from TS, nevertheless, I provide 1 (number) which looks like is not accepted.

Type 'number' is not assignable to type '1 | -1 | { $meta: "textScore"; }'

Before migration, I did not encounter this error and compilation/code execution was fine.

Please, let me know what am I am missing.

I'm currently facing the same issue and as a workaround I came up with this:

const sort: Record<string, | 1 | -1 | {$meta: "textScore"}> = { reference: 1 };

export const timetableTest = (group: string): Promise<IGroupTimetableEvents[]> => {
    const agg = [{ $match: { group } }, { $sort: sort }];
    const result = GroupEvent.aggregate(agg).exec();
    return result;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM