title: Mongoose TypeScript ObjectId casting - Type 'string' is not assignable to type 'Condition<ObjectId | undefined>'
body: <p>I am having issues with mongoose queries when I query by an ObjectId field. Passing <code>mongoose.Types.ObjectId</code> or <code>string</code> both throws errors. TypeScript only stops complaining when I cast the ObjectId to <code>mongoose.Schema.Types.ObjectId</code>, which then crashes at runtime since it's not a valid ObjectId.</p>
  <pre><code>interface DocumentWithTimestamp extends Document&lt;ObjectId&gt; {
    createdAt: Date;
    updatedAt: Date;
  }
  </code></pre>
  <p>First of all, I noticed that Document defines <code>_id</code> as <code>ObjectId | undefined</code>, which already complicates everything.</p>
  <p>I define my Schemas as follows:</p>
  <pre><code>export interface LanguageSchema extends DocumentWithTimestamp {
    langCode: string;
    locale: string;
  }
  
  
  interface LanguageModel extends Model&lt;LanguageSchema&gt; {
    mapToLanguage(language: LeanDocument&lt;LanguageSchema&gt; | LanguageSchema): Language;
  }
  
  const languageSchema = new Schema&lt;LanguageSchema, LanguageModel&gt;(
    {
      langCode: { type: String, required: true, trim: true },
      locale: { type: String, unique: true, required: true, trim: true },
    },
    { collection: 'language', timestamps: true, versionKey: false },
  );
  
  languageSchema.statics.mapToLanguage = function (language: LeanDocument&lt;LanguageSchema&gt; | LanguageSchema): Language {
    return {
      id: language._id?.toString() || '', // why is _id conditional...?
      langCode: language.langCode,
      locale: language.locale,
    };
  };
  
  export const LanguageModel = model&lt;LanguageSchema, LanguageModel&gt;('Language', languageSchema);
  </code></pre>
  <p>Now querying my LanguageModel by _id or any other ObjectId field throws type errors:</p>
  <pre><code>export async function findLanguagesByIds(languageIds: string[]) {
    return LanguageModel.find({ _id: { $in: languageIds } }).lean();
  }
  </code></pre>
  <p>Error:</p>
  <pre><code>Argument of type '{ _id: { $in: string[]; }; }' is not assignable to parameter of type 'Callback&lt;LanguageSchema[]&gt;'.
        Object literal may only specify known properties, and '_id' does not exist in type 'Callback&lt;LanguageSchema[]&gt;'.
  </code></pre>
  <p>When I try to cast string[] to Schema.Types.ObjectId[] array, the error goes away but this cannot be the solution, since it crashes at runtime (Schema.Types.ObjectId is not a valid ObjectId).</p>
  <pre><code>const languages = await LanguageModel.find({
    _id: { $in: languageIds.map((id) =&gt; new mongoose.Schema.Types.ObjectId(id)) },
  }).lean();
  </code></pre>
  <p>If I cast to <code>mongoose.Types.ObjectId</code>(to a real ObjectId) it throws errors again...</p>
  <p>Any help is appreciated!</p>