-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Why findById returns (User & { _id: Schema.Types.ObjectId; }) | null they User | null #10987
Comments
What is ObjectId in your document definition, Types.ObjectId or Schema.Types.ObjectId? |
that's how I do the import |
I've the same code except that _id is any in the interface, the return type of a findOne is:
I think it should be |
The return type comes from the internal types used by Mongoose's Because the
@Darfion - I believe if you just change the Also, a couple potential issues in the provided examples: export interface User extends Document { ... }
const User = model<User>('user', UserSchema, 'users'); At least in my VS Code with my tsconfig.json, this causes a naming conflict between the const userSchema = new Schema<User>({ ... });
const User = model<User>('user', UserSchema, 'users'); In the above, I rewrote the example like this and it works as expected in my testing: import { Types, model, Document, Schema } from 'mongoose';
export interface IUser extends Document {
_id: Types.ObjectId;
lastName: string;
}
const userSchema = new Schema<IUser>({
lastName: { type: String, required: true, trim: true },
});
const User = model('user', userSchema, 'users');
const user = await User.findById(userId).exec(); // user: HydratedDocument<IUser, {}, {}> | null
if (user) user._id; // user._id: Types.ObjectId |
Thanks for explanation. I think on line 8 you mean |
I did, thanks! Fixed it. Also fixed where I'd been referring to TypeScript unions (which is |
@drewkht 's comment #10987 (comment) is correct. We added a note about the |
This is my first time using typescript and mongoose. Here's my code
type
Schema
model
request
I expect the
user
variable to be of typeUser | null
.but i get(User & {_id: Schema.Types.ObjectId;}) | null
. If I don't declare _id: ObjectId; then I get ( User & { _id: any; }) | null. I do not know if this is some kind of mistake or it should be like thisThe text was updated successfully, but these errors were encountered: