mongoose: MongoDB IndexOptions type is missing
Do you want to request a feature or report a bug? Bug
What is the current behavior? If the current behavior is a bug, please provide the steps to reproduce.
In Schema.index
second parameter, { unique: true }
was marked as invalid because unique
is not a member of Mongoose’s IndexOption
interface.
import { model, Schema } from "mongoose";
export interface User {
email?: string;
password?: string;
createdAt?: Date;
updatedAt?: Date;
}
const UserSchema = new Schema<User>(
{
email: { type: String, required: true },
password: { type: String, required: true },
},
{ timestamps: true }
);
UserSchema.index({ email: 1, campaign: 1 }, { unique: true });
export default model<User>("User", UserSchema);
EDIT: See it on StackBlitz
The Mongoose’s interface extends MongoDB’s IndexOptions
interface, which was not available in @types/mongodb
version 3.6.20
resolved as a Mongoose dependency by NPM.
Manually installing an updated package (version 4.0.7
) fixed the error.
What is the expected behavior?
Using unique
and other index options should be TS-compilable.
What are the versions of Node.js, Mongoose and MongoDB you are using? Note that “latest” is not a version.
- Node.js:
14.17.3
- Mongoose:
5.13.7
- MongoDB:
4.1.0
- TypeScript:
4.3.5
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 1
- Comments: 19
Commits related to this issue
- test(typescript): add coverage for #10590 — committed to Automattic/mongoose by vkarpov15 3 years ago
My fix was to put this in my package.json:
Figured out that some other package was also depending on v4 types, which were apparently not compatible with my mongoose version v5.9.
This fix probably also works with slightly different mongoose and mongodb versions, but those are the ones I used
@rlawisch in your provided example, if you try to
Go to Definition
(to open mongoose’sindex.d.ts
) onUserSchema.index
and then go to the top of the page, you can see the errorCannot find module 'mongodb' or its corresponding type declarations.(2307)
, which means thatstackblitz
is not properly installing (type) packages