field with Types.ObjectId has typescript error in Schema
See original GitHub issuePrerequisites
- I have written a descriptive issue title
Mongoose version
6.5.4
Node.js version
16.14.2
MongoDB version
doesn’t matter
Operating system
macOS
Operating system version (i.e. 20.04, 11.3, 10)
12.5.1
Issue
import { Schema, Types } from 'mongoose';
interface Foo {
_id: Types.ObjectId,
bar: Types.ObjectId,
}
const FooSchema = new Schema<Foo>({
_id: { type: Types.ObjectId },
bar: { type: Types.ObjectId },
});
property _id
and bar
has typescript error:
Type '{ type: typeof Types.ObjectId; }' is not assignable to type 'SchemaDefinitionProperty<ObjectId> | undefined'.
Types of property 'type' are incompatible.
Type 'typeof ObjectId' is not assignable to type 'typeof Mixed | ObjectIdSchemaDefinition | undefined'.ts(2322)
But I cannot figure out why, and don’t know how to solve it.
Issue Analytics
- State:
- Created a year ago
- Comments:8
Top Results From Across the Web
Mongoose TypeScript ObjectId casting - Type 'string' is not ...
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...
Read more >Populate with TypeScript - Mongoose
Mongoose's TypeScript bindings add a generic parameter Paths to the populate() : import { Schema, model, Document, Types } from 'mongoose'; ...
Read more >Error & Warning Details - typegoose
This Error may get thrown when a invalid Type is used with the option enum . Currently Valid Types for enum are String...
Read more >TypeScript — Node.js - MongoDB
The type error raised by the preceding code snippet is as follows: ... How you specify the _id field in type parameters passed...
Read more >Express Tutorial Part 3: Using a Database (with Mongoose)
The documents will contain the fields/schema types defined in the model ... If the query is successful, the error parameter will be null, ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
sorry that i didnt see that before, but yes it seems like mongoose currently does not translate
mongoose.Schema.Types.*
tomongoose.Types.*
in types and you have to use the latter for the types, but the former for the Schema itself (innew Schema(here)
)the proper type should be
type YourDocument = mongoose.Document<IdType> & YourSchema
, also see Mongoose Documentation: Typescriptsee typegoose’s implementation for a full (generic) example: https://github.com/typegoose/typegoose/blob/06f710df2d47a7501a496dc877dce955e047fe2b/src/types.ts#L14-L18