-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Description
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the bug has not already been reported
Mongoose version
6.x.x
Node.js version
14.x
MongoDB server version
5.x
Typescript version (if applicable)
4.8.x
Description
When creating a new document with a Mongoose model, the _id field is automatically generated as a Types.ObjectId. Assigning this _id to a variable of type number causes a TypeScript type error.
This occurs even though some example tests try to assert this assignment with expectError((_id: number) = newUser._id) which is invalid syntax.
This is a TypeScript type-check issue, not a runtime error, but can be confusing for developers using Mongoose with TypeScript.
Steps to Reproduce
import { expectError } from 'tsd';
interface User {
username: string;
email: string;
}
const userSchema = new Schema<User>({
username: String,
email: String
});
const UserModel = model('User', userSchema);
const newUser = new UserModel();
// Attempt to assign _id to a number (TS error)
let _id: number;
_id = newUser._id; // TypeScript error: ObjectId is not assignable to number
// Correct way to test type error with tsd
expectError(() => {
const _id: number = newUser._id;
});
// Valid assignment
const _id2: Types.ObjectId = newUser._id;
Expected Behavior
TypeScript should correctly enforce that _id is of type Types.ObjectId.
Assignments like const _id: number = newUser._id should fail, as expected.
The existing test examples using expectError((_id: number) = newUser._id) should be updated to use the correct callback syntax:
expectError(() => {
const _id: number = newUser._id;
});```