Skip to content

Commit 61595f0

Browse files
committedDec 8, 2020
fix(index.d.ts): allow passing ObjectId properties as strings to create() and findOneAndReplace()
Fix #9676
1 parent 8a52485 commit 61595f0

File tree

3 files changed

+8
-3
lines changed

3 files changed

+8
-3
lines changed
 

‎index.d.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -2110,7 +2110,10 @@ declare module "mongoose" {
21102110

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

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

21152118
type FunctionPropertyNames<T> = {
21162119
// The 1 & T[K] check comes from: https://stackoverflow.com/questions/55541275/typescript-check-for-the-any-type

‎test/typescript/create.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
1-
import { Schema, model, Document } from 'mongoose';
1+
import { Schema, model, Document, Types } from 'mongoose';
22

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

55
interface ITest extends Document {
6+
_id?: Types.ObjectId;
67
name?: string;
78
}
89

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

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

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

‎test/typescript/queries.ts

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const Test = model<ITest>('Test', schema);
1313
Test.count({ name: /Test/ }).exec().then((res: number) => console.log(res));
1414

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

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

0 commit comments

Comments
 (0)
Please sign in to comment.