'MongoDB, $text with projection score meta seems to be broken

I'm trying to apply projection to a score based text search while maintaining the score value.

Seems to be broken.

The following does not maintain the score property.

export const searchUsers = async (searchTerm: string): Promise<UserLight[]> => {
    const nGrams = createEdgeNGrams(searchTerm);
    const projection = { ...userLightProjection, ...{ score: 1 } };
    const users = await UserModel.find(
        {
            $text: {
                $search: nGrams,
            },

            // TODO Potentially very slow; test on 3m users.
            // TODO Look into replacing with $text
            // or: [
            //     { username: new RegExp(searchTerm, "i") }, //
            //     { phoneNumber: new RegExp(searchTerm, "i") },
            // ],
        },
        { score: { $meta: "textScore" } },
        {
            // TODO: Score is not reserved..
            projection,
        }
        // userLightProjection
    )
        // .sort({ lastPlatformActionIso: -1 })
        .limit(50);

    // @ts-ignore
    return users;
};


Sources

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

Source: Stack Overflow

Solution Source