Skip to content

Type is incorrect for Query.distinct when field is a nested field #14615

Closed
@bpabel

Description

@bpabel

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.1.2

Node.js version

18.x

MongoDB server version

4.2.8

Typescript version (if applicable)

No response

Description

When using the distinct query for nested fields, the declared type of the return value is unknown[], even though the type should be statically discoverable as string[].

A minimal example

myrecord.schema.ts

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';


@Schema()
export class Foo {
  @Prop()
  one: string;
}

export const FooSchema = SchemaFactory.createForClass(Foo);


@Schema()
export class MyRecord extends Document {

  @Prop()
  _id: string;

  @Prop({ type: FooSchema })
  foo: Foo;

export const MyRecordSchema = SchemaFactory.createForClass(MyRecord);

myrecord.service.ts

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { MyRecord } from '../schemas/myrecord.schema';

@Injectable()
export class MyService {
  constructor(
    @InjectModel('myrecord') private model: Model<MyRecord>,
  ) {}

  async myQuery(): Promise<void> {
    const foos: string[] = await this.model.distinct('foo.one').exec()
  }

}

The type checking error shows:

Type 'unknown[]' is not assignable to type 'string[]'

Steps to Reproduce

I've included some sample code above. It's written in the style of nestjs, so it may need to be modified a bit for a simpler use case without nestjs.

  1. Create a document schema with a subdocument.
  2. Write a distinct query for the document on one of the nested fields on the subdocument.
  3. The specified return type will be unknown[]

Expected Behavior

The resolved return type should be an array of the subdocument field type. In this case, string[].

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions