Git Product home page Git Product logo

Comments (3)

alukach avatar alukach commented on July 21, 2024

I could do something like this:

export const getParents = async (): Promise<ExpectedParent[]> => {
  const parents = await ParentModel.find<ExpectedParent>();
  return parents;
};

However, this seems a bit heavy-handed as I am now overriding the entirety of the types stored within the mongoose schemas.

I ended up landing on this utility type:

// Recursive type to enforce `_id` in all subdocuments
type EnforceIdInSubdocuments<T> = {
  [K in keyof T]: T[K] extends mongoose.Types.DocumentArray<infer U>
    ? mongoose.Require_id<U>[]
    : T[K] extends object
    ? EnforceIdInSubdocuments<T[K]>
    : T[K];
};

// Utility type to extract and enforce _id in subdocuments
type ModelWithEnforcedIds<T extends mongoose.Model<any>> = EnforceIdInSubdocuments<
  mongoose.InferSchemaType<T['schema']>
>;

Full example:

import mongoose from 'mongoose';

const ChildSchema = new mongoose.Schema({
  name: { type: String, required: true },
});

const ParentSchema = new mongoose.Schema({
  _id: { type: String, required: true },
  name: { type: String, required: true },
  parts: { type: [ChildSchema] },
});

const ParentModel = mongoose.model('Parent', ParentSchema);


export const getParents = async (): Promise<ExpectedParent[]> => {
  const parents = await ParentModel.find<ModelWithEnforcedIds<typeof ParentModel>>();
  return parents;
};

interface ExpectedParent {
  _id: string;
  name: string;
  parts: Array<{ _id: string; name: string }>;
}

// Recursive type to enforce `_id` in all subdocuments
type EnforceIdInSubdocuments<T> = {
  [K in keyof T]: T[K] extends mongoose.Types.DocumentArray<infer U>
    ? mongoose.Require_id<U>[]
    : T[K] extends object
    ? EnforceIdInSubdocuments<T[K]>
    : T[K];
};

// Utility type to extract and enforce _id in subdocuments
type ModelWithEnforcedIds<T extends mongoose.Model<any>> = EnforceIdInSubdocuments<
  mongoose.InferSchemaType<T['schema']>
>;

I will leave this open as I feel like there's probably a better way to do this.

from mongoose.

vkarpov15 avatar vkarpov15 commented on July 21, 2024

This looks like expected behavior: you expect your parts subdocs to have _id: string, but you don't define an _id property in ChildSchema, so Mongoose assumes that parts subdocs have ObjectId _id's. To make this script compile correctly, just add an _id property below:

const ChildSchema = new mongoose.Schema({
  _id: { type: String, required: true }, // <-- add _id here
  name: { type: String, required: true },
});

Or, if you intend to have ObjectId _id for ChildSchema, do the following:

const ChildSchema = new mongoose.Schema({
  _id: { type: 'ObjectId', required: true }, // <-- change _id type here
  name: { type: String, required: true },
});

interface ExpectedParent {
  _id: string;
  name: string;
  parts: Array<{ _id: mongoose.Types.ObjectId; name: string }>; // <-- change _id type here
}

Does this help?

from mongoose.

alukach avatar alukach commented on July 21, 2024

Thanks for the reply @vkarpov15.

This looks like expected behavior: you expect your parts subdocs to have _id: string, but you don't define an _id property in ChildSchema, so Mongoose assumes that parts subdocs have ObjectId _id's

From my vantage point, the issue is that Mongoose's types do not assume that the parts subdocs have ObjectId _id's.

As you are aware, each subdocument has an _id by default. However, the TS logic does not demonstrate this. I wouldn't classify that as "expected behavior". I do understand that I could change my schema to coerce the type system to acknowledge an _id property, but that seems more like a work-around. If the Mongoose docs & code are written so that an _id is to be assumed, I believe the corresponding types should reflect that (hence my view that this is a bug).

from mongoose.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.