Skip to content

Commit

Permalink
fix(index.d.ts): allow passing ObjectId properties as strings to `cre…
Browse files Browse the repository at this point in the history
…ate()` and `findOneAndReplace()`

Fix #9676
  • Loading branch information
vkarpov15 committed Dec 8, 2020
1 parent 8a52485 commit 61595f0
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 3 deletions.
5 changes: 4 additions & 1 deletion index.d.ts
Expand Up @@ -2110,7 +2110,10 @@ declare module "mongoose" {

export type UpdateQuery<T> = mongodb.UpdateQuery<DocumentDefinition<T>> & mongodb.MatchKeysAndValues<DocumentDefinition<T>>;

export type DocumentDefinition<T> = Omit<T, Exclude<keyof Document, '_id'>>;
type _AllowStringsForIds<T> = {
[K in keyof T]: [Extract<T[K], mongodb.ObjectId>] extends [never] ? T[K] : T[K] | string;
};
export type DocumentDefinition<T> = _AllowStringsForIds<Omit<T, Exclude<keyof Document, '_id'>>>;

type FunctionPropertyNames<T> = {
// The 1 & T[K] check comes from: https://stackoverflow.com/questions/55541275/typescript-check-for-the-any-type
Expand Down
5 changes: 3 additions & 2 deletions test/typescript/create.ts
@@ -1,14 +1,15 @@
import { Schema, model, Document } from 'mongoose';
import { Schema, model, Document, Types } from 'mongoose';

const schema: Schema = new Schema({ name: { type: 'String' } });

interface ITest extends Document {
_id?: Types.ObjectId;
name?: string;
}

const Test = model<ITest>('Test', schema);

Test.create({ name: 'test' }).then((doc: ITest) => console.log(doc.name));
Test.create({ _id: '0'.repeat(24), name: 'test' }).then((doc: ITest) => console.log(doc.name));

Test.create([{ name: 'test' }], { validateBeforeSave: false }).then((docs: ITest[]) => console.log(docs[0].name));

Expand Down
1 change: 1 addition & 0 deletions test/typescript/queries.ts
Expand Up @@ -13,6 +13,7 @@ const Test = model<ITest>('Test', schema);
Test.count({ name: /Test/ }).exec().then((res: number) => console.log(res));

Test.find({ parent: new Types.ObjectId('0'.repeat(24)) });
Test.find({ parent: '0'.repeat(24) });

Test.find({ name: { $in: ['Test'] } }).exec().then((res: Array<ITest>) => console.log(res));

Expand Down

0 comments on commit 61595f0

Please sign in to comment.