乐闻世界logo
搜索文章和话题

How to define mongoose _id in TypeScript interface?

1个答案

1

When using TypeScript with Mongoose, you can define the _id property by extending the Document interface. Every document in Mongoose has a default _id property, which is typically of the ObjectId type. However, in TypeScript, you need to explicitly declare this property in the interface to achieve type safety and IntelliSense hints.

Here is an example of how to define the _id property in a TypeScript interface:

typescript
import mongoose, { Document, ObjectId } from 'mongoose'; interface IUser extends Document { _id: ObjectId; // Explicitly declare the `_id` property username: string; email: string; // Other user properties } // Define the user's Schema const UserSchema = new mongoose.Schema({ username: { type: String, required: true }, email: { type: String, required: true }, // Other field definitions }); // Create the model const UserModel = mongoose.model<IUser>('User', UserSchema); // Use the model const user = new UserModel({ username: 'johndoe', email: 'johndoe@example.com' }); console.log(user._id); // Safely use the `_id` property, as TypeScript knows it's of the `ObjectId` type

In this example, the IUser interface extends Document from the mongoose package, allowing you to leverage Mongoose's built-in _id and other document methods. We explicitly declare _id as the ObjectId type in the IUser interface, which is the default type generated by Mongoose.

This enables TypeScript to provide type checking and IntelliSense for the _id property when using UserModel to create new users or manipulate document data. In real-world CRUD operations, such type definitions help prevent common type-related errors.

2024年6月29日 12:07 回复

你的答案