Skip to content

string type assignment fails for ObjectId in nested subdocuments #16362

Description

@E1ecti

Prerequisites

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

Mongoose version

9.7.3

Node.js version

26.4.0

MongoDB server version

Unrelated

Typescript version (if applicable)

6.0.3

Description

Related to #16316.

When using nested interfaces (for example, when using class-validator where subdocuments are defined by separate classes), the error Index signature for type 'string' is missing in type 'N' occurs, or Type 'string' is not assignable to type 'ObjectId ...' in the case of nested arrays.

This issue only affects cases where string is used instead of mongoose.Types.ObjectId.

It can also be solved by adding [x: string]: {} to the validation class, however, this is not a suitable solution.

Steps to Reproduce

import * as mongoose from "mongoose"

interface User {
	dummy: string
}

interface Other {
	nested: {
		to: mongoose.PopulatedDoc<User>
	}
}

interface Nested {
	to: string
}
interface OtherNested {
	nested: Nested
}

const userSchema = new mongoose.Schema({ dummy: String })
const userModel = mongoose.model<User>("user", userSchema)

const otherSchema = new mongoose.Schema({
	nested: {
		to: { type: mongoose.Types.ObjectId, ref: "user" }
	}
})
const otherModel = mongoose.model<Other>("other", otherSchema)

async function main() {
	const user = await userModel.create({ dummy: "hello" })

	const userId = user._id.toString()
	const data: OtherNested = { nested: { to: userId } }

	// Index signature for type 'string' is missing in type 'Nested'.
	const other = await otherModel.create(data)

	console.log("Done", other)

	await mongoose.disconnect()
}

main()

Expected Behavior

Using string should be acceptable as using ObjectId inside subdocuments during creation.

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