Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/tsd.yml → .github/workflows/types.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ name: Typescript Types
on:
pull_request:
paths:
- '.github/workflows/tsd.yml'
- '.github/workflows/types.yml'
- 'package.json'
- 'types/**'
- 'test/types/**'
push:
paths:
- '.github/workflows/tsd.yml'
- '.github/workflows/types.yml'
- 'package.json'
- 'types/**'
- 'test/types/**'
Expand Down Expand Up @@ -48,4 +48,4 @@ jobs:
- run: npm install

- name: Typings
run: npm run test-tsd
run: npm run test:types
16 changes: 1 addition & 15 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@
"nyc": "15.1.0",
"pug": "3.0.3",
"sinon": "21.0.1",
"tsd": "0.33.0",
"typescript": "5.9.3",
"typescript-eslint": "^8.31.1",
"uuid": "11.1.0"
Expand Down Expand Up @@ -99,7 +98,7 @@
"test-deno:ci": "npm run test-deno -- --reporter min",
"test-rs": "START_REPLICA_SET=1 mocha --timeout 30000 --exit ./test/*.test.js",
"test-rs:ci": "npm run test-rs -- --reporter min",
"test-tsd": "node ./test/types/check-types-filename && tsd --full",
"test:types": "tsc --project test/types/tsconfig.json",
"setup-test-encryption": "node scripts/setup-encryption-tests.js",
"test-encryption": "mocha --exit ./test/encryption/*.test.js",
"test-encryption:ci": "npm run test-encryption -- --reporter min",
Expand Down Expand Up @@ -131,18 +130,5 @@
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/mongoose"
},
"tsd": {
"directory": "test/types",
"compilerOptions": {
"esModuleInterop": false,
"strict": true,
"allowSyntheticDefaultImports": true,
"strictPropertyInitialization": false,
"noImplicitAny": false,
"strictNullChecks": true,
"module": "commonjs",
"target": "ES2022"
}
}
}
1 change: 0 additions & 1 deletion test/types/PipelineStage.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { ObjectId } from 'mongodb';
import type { PipelineStage } from 'mongoose';
import { expectError, expectType } from 'tsd';

/**
* $addFields:
Expand Down
34 changes: 17 additions & 17 deletions test/types/aggregate.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Schema, model, Document, Expression, PipelineStage, Types, Model, Aggregate } from 'mongoose';
import { expectType } from 'tsd';
import { ExpectType } from './util/assertions';

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

Expand All @@ -25,8 +25,8 @@ async function run() {
const res2: Array<ITest> = await Test.aggregate<ITest>([{ $match: { name: 'foo' } }]);
console.log(res2[0].name);

expectType<number | undefined>(Test.aggregate<ITest>([{ $match: { name: 'foo' } }]).options.maxTimeMS);
expectType<boolean | undefined>(Test.aggregate<ITest>([{ $match: { name: 'foo' } }]).options.allowDiskUse);
ExpectType<number | undefined>(Test.aggregate<ITest>([{ $match: { name: 'foo' } }]).options.maxTimeMS);
ExpectType<boolean | undefined>(Test.aggregate<ITest>([{ $match: { name: 'foo' } }]).options.allowDiskUse);
Test.aggregate<ITest>([{ $match: { name: 'foo' } }]).option({ maxTimeMS: 222 });

await Test.aggregate<ITest>([{ $match: { name: 'foo' } }]).cursor().eachAsync(async(res) => {
Expand All @@ -39,32 +39,32 @@ async function run() {

function eachAsync(): void {
Test.aggregate().cursor().eachAsync((doc) => {
expectType<any>(doc);
ExpectType<any>(doc);
});
Test.aggregate().cursor().eachAsync((docs) => {
expectType<any[]>(docs);
ExpectType<any[]>(docs);
}, { batchSize: 2 });
Test.aggregate().cursor<ITest>().eachAsync((doc) => {
expectType<ITest>(doc);
ExpectType<ITest>(doc);
});
Test.aggregate().cursor<ITest>().eachAsync((docs) => {
expectType<ITest[]>(docs);
ExpectType<ITest[]>(docs);
}, { batchSize: 2 });
}

// Aggregate.prototype.sort()
expectType<ITest[]>(await Test.aggregate<ITest>().sort('-name'));
expectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: 1 }));
expectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: -1 }));
expectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: 'asc' }));
expectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: 'ascending' }));
expectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: 'desc' }));
expectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: 'descending' }));
expectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: { $meta: 'textScore' } }));
ExpectType<ITest[]>(await Test.aggregate<ITest>().sort('-name'));
ExpectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: 1 }));
ExpectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: -1 }));
ExpectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: 'asc' }));
ExpectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: 'ascending' }));
ExpectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: 'desc' }));
ExpectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: 'descending' }));
ExpectType<ITest[]>(await Test.aggregate<ITest>().sort({ name: { $meta: 'textScore' } }));

// Aggregate.prototype.model()
expectType<Model<any>>(Test.aggregate<ITest>().model());
expectType<Aggregate<ITest[]>>(Test.aggregate<ITest>().model(AnotherTest));
ExpectType<Model<any>>(Test.aggregate<ITest>().model());
ExpectType<Aggregate<ITest[]>>(Test.aggregate<ITest>().model(AnotherTest));
}

function gh12017_1() {
Expand Down
9 changes: 5 additions & 4 deletions test/types/base.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as mongoose from 'mongoose';
import { expectError, expectType } from 'tsd';
import { ExpectType } from './util/assertions';

Object.values(mongoose.models).forEach(model => {
model.modelName;
Expand All @@ -23,14 +23,14 @@ function gh10746() {
let testVar: A;
testVar = 'A string';
testVar = 'B string';
expectType<string>(testVar);
ExpectType<string>(testVar);
}

function gh10957() {
type TestType = { name: string };
const obj: TestType = { name: 'foo' };

expectType<TestType>(mongoose.trusted(obj));
ExpectType<TestType>(mongoose.trusted(obj));
}

function connectionStates() {
Expand Down Expand Up @@ -73,7 +73,8 @@ function setAsObject() {
updatePipeline: true
});

expectError(mongoose.set({ invalid: true }));
// @ts-expect-error should error out if an invalid option is provided
mongoose.set({ invalid: true });
}

const x: { name: string } = mongoose.omitUndefined({ name: 'foo' });
Expand Down
8 changes: 4 additions & 4 deletions test/types/connect.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import mongoose, { connect } from 'mongoose';
import { expectType } from 'tsd';
import { ExpectType } from './util/assertions';

// Promise
expectType<Promise<typeof mongoose>>(connect('mongodb://127.0.0.1:27017/test'));
expectType<Promise<typeof mongoose>>(connect('mongodb://127.0.0.1:27017/test', {}));
expectType<Promise<typeof mongoose>>(connect('mongodb://127.0.0.1:27017/test', { bufferCommands: true }));
ExpectType<Promise<typeof mongoose>>(connect('mongodb://127.0.0.1:27017/test'));
ExpectType<Promise<typeof mongoose>>(connect('mongodb://127.0.0.1:27017/test', {}));
ExpectType<Promise<typeof mongoose>>(connect('mongodb://127.0.0.1:27017/test', { bufferCommands: true }));
127 changes: 68 additions & 59 deletions test/types/connection.test.ts
Original file line number Diff line number Diff line change
@@ -1,87 +1,93 @@
import { createConnection, Schema, Collection, Connection, ConnectionSyncIndexesResult, InferSchemaType, Model, connection, HydratedDocument, Query } from 'mongoose';
import * as mongodb from 'mongodb';
import { expectAssignable, expectError, expectType } from 'tsd';
import { AutoTypedSchemaType, autoTypedSchema } from './schema.test';
import { ExpectAssignable, ExpectType } from './util/assertions';

expectType<Connection>(createConnection());
expectType<Connection>(createConnection('mongodb://127.0.0.1:27017/test'));
expectType<Connection>(createConnection('mongodb://127.0.0.1:27017/test', { appName: 'mongoose' }));
ExpectType<Connection>(createConnection());
ExpectType<Connection>(createConnection('mongodb://127.0.0.1:27017/test'));
ExpectType<Connection>(createConnection('mongodb://127.0.0.1:27017/test', { appName: 'mongoose' }));

const conn = createConnection();

expectAssignable<Model<{ name: string }, any, any, any>>(conn.model('Test', new Schema<{ name: string }>({ name: { type: String } })));
expectType<Model<{ name: string }>>(conn.model<{ name: string }>('Test', new Schema({ name: { type: String } })));
ExpectAssignable<Model<{ name: string }, any, any, any>>()(conn.model('Test', new Schema<{ name: string }>({ name: { type: String } })));
ExpectType<Model<{ name: string }>>(conn.model<{ name: string }>('Test', new Schema({ name: { type: String } })));

expectType<Promise<Connection>>(conn.openUri('mongodb://127.0.0.1:27017/test'));
expectType<Promise<Connection>>(conn.openUri('mongodb://127.0.0.1:27017/test', { bufferCommands: true }));
ExpectType<Promise<Connection>>(conn.openUri('mongodb://127.0.0.1:27017/test'));
ExpectType<Promise<Connection>>(conn.openUri('mongodb://127.0.0.1:27017/test', { bufferCommands: true }));

conn.readyState === 0;
conn.readyState === 99;

expectError(conn.readyState = 0);
// @ts-expect-error should not be allowed to update readyState
conn.readyState = 0;

expectType<Promise<Record<string, Error | mongodb.Collection<any>>>>(
ExpectType<Promise<Record<string, Error | mongodb.Collection<any>>>>(
conn.createCollections()
);

expectType<Connection>(new Connection());
expectType<Promise<Connection>>(new Connection().asPromise());
ExpectType<Connection>(new Connection());
ExpectType<Promise<Connection>>(new Connection().asPromise());

expectType<Promise<mongodb.Collection<{ [key: string]: any }>>>(conn.createCollection('some'));
ExpectType<Promise<mongodb.Collection<{ [key: string]: any }>>>(conn.createCollection('some'));

expectType<Promise<void>>(conn.dropCollection('some'));
ExpectType<Promise<void>>(conn.dropCollection('some'));

expectError(conn.deleteModel());
expectType<Connection>(conn.deleteModel('something'));
expectType<Connection>(conn.deleteModel(/.+/));
// @ts-expect-error cannot call deleteModel with no args
conn.deleteModel();
ExpectType<Connection>(conn.deleteModel('something'));
ExpectType<Connection>(conn.deleteModel(/.+/));

expectType<Array<string>>(conn.modelNames());
ExpectType<Array<string>>(conn.modelNames());

expectType<Promise<void>>(createConnection('mongodb://127.0.0.1:27017/test').close());
expectType<Promise<void>>(createConnection('mongodb://127.0.0.1:27017/test').close(true));
ExpectType<Promise<void>>(createConnection('mongodb://127.0.0.1:27017/test').close());
ExpectType<Promise<void>>(createConnection('mongodb://127.0.0.1:27017/test').close(true));

expectType<mongodb.Db | undefined>(conn.db);
ExpectType<mongodb.Db | undefined>(conn.db);

expectType<mongodb.MongoClient>(conn.getClient());
expectType<Connection>(conn.setClient(new mongodb.MongoClient('mongodb://127.0.0.1:27017/test')));
ExpectType<mongodb.MongoClient>(conn.getClient());
ExpectType<Connection>(conn.setClient(new mongodb.MongoClient('mongodb://127.0.0.1:27017/test')));

expectType<Promise<string>>(conn.transaction(async(res) => {
expectType<mongodb.ClientSession>(res);
ExpectType<Promise<string>>(conn.transaction(async(res) => {
ExpectType<mongodb.ClientSession>(res);
return 'a';
}));
expectType<Promise<string>>(conn.transaction(async(res) => {
expectType<mongodb.ClientSession>(res);
ExpectType<Promise<string>>(conn.transaction(async(res) => {
ExpectType<mongodb.ClientSession>(res);
return 'a';
}, { readConcern: 'majority' }));

expectType<Promise<string>>(conn.withSession(async(res) => {
expectType<mongodb.ClientSession>(res);
ExpectType<Promise<string>>(conn.withSession(async(res) => {
ExpectType<mongodb.ClientSession>(res);
return 'a';
}));

expectError(conn.user = 'invalid');
expectError(conn.pass = 'invalid');
expectError(conn.host = 'invalid');
expectError(conn.port = 'invalid');
// @ts-expect-error cannot update user property
conn.user = 'invalid';
// @ts-expect-error cannot update pass property
conn.pass = 'invalid';
// @ts-expect-error cannot update host property
conn.host = 'invalid';
// @ts-expect-error cannot update port property
conn.port = 'invalid';

expectType<Collection>(conn.collection('test'));
expectType<mongodb.Collection | undefined>(conn.db?.collection('test'));
ExpectType<Collection>(conn.collection('test'));
ExpectType<mongodb.Collection | undefined>(conn.db?.collection('test'));

expectType<Promise<mongodb.ClientSession>>(conn.startSession());
expectType<Promise<mongodb.ClientSession>>(conn.startSession({ causalConsistency: true }));
ExpectType<Promise<mongodb.ClientSession>>(conn.startSession());
ExpectType<Promise<mongodb.ClientSession>>(conn.startSession({ causalConsistency: true }));

expectType<Promise<ConnectionSyncIndexesResult>>(conn.syncIndexes());
expectType<Promise<ConnectionSyncIndexesResult>>(conn.syncIndexes({ continueOnError: true }));
ExpectType<Promise<ConnectionSyncIndexesResult>>(conn.syncIndexes());
ExpectType<Promise<ConnectionSyncIndexesResult>>(conn.syncIndexes({ continueOnError: true }));

expectType<Connection>(conn.useDb('test'));
expectType<Connection>(conn.useDb('test', {}));
expectType<Connection>(conn.useDb('test', { useCache: true }));
ExpectType<Connection>(conn.useDb('test'));
ExpectType<Connection>(conn.useDb('test', {}));
ExpectType<Connection>(conn.useDb('test', { useCache: true }));

expectType<Promise<string[]>>(
ExpectType<Promise<string[]>>(
conn.listCollections().then(collections => collections.map(coll => coll.name))
);

expectType<Promise<string[]>>(
ExpectType<Promise<string[]>>(
conn.listDatabases().then(dbs => dbs.databases.map(db => db.name))
);

Expand All @@ -93,22 +99,22 @@ export function autoTypedModelConnection() {
// Model-functions-test
// Create should works with arbitrary objects.
const randomObject = await AutoTypedModel.create({ unExistKey: 'unExistKey', description: 'st' } as Partial<InferSchemaType<typeof AutoTypedSchema>>);
expectType<AutoTypedSchemaType['schema']['userName']>(randomObject.userName);
ExpectType<AutoTypedSchemaType['schema']['userName']>(randomObject.userName);

const testDoc1 = await AutoTypedModel.create({ userName: 'M0_0a' });
expectType<AutoTypedSchemaType['schema']['userName']>(testDoc1.userName);
expectType<AutoTypedSchemaType['schema']['description']>(testDoc1.description);
ExpectType<AutoTypedSchemaType['schema']['userName']>(testDoc1.userName);
ExpectType<AutoTypedSchemaType['schema']['description']>(testDoc1.description);

const testDoc2 = await AutoTypedModel.insertMany([{ userName: 'M0_0a' }]);
expectType<AutoTypedSchemaType['schema']['userName']>(testDoc2[0].userName);
expectType<AutoTypedSchemaType['schema']['description'] | undefined>(testDoc2[0]?.description);
ExpectType<AutoTypedSchemaType['schema']['userName']>(testDoc2[0].userName);
ExpectType<AutoTypedSchemaType['schema']['description'] | undefined>(testDoc2[0]?.description);

const testDoc3 = await AutoTypedModel.findOne({ userName: 'M0_0a' });
expectType<AutoTypedSchemaType['schema']['userName'] | undefined>(testDoc3?.userName);
expectType<AutoTypedSchemaType['schema']['description'] | undefined>(testDoc3?.description);
ExpectType<AutoTypedSchemaType['schema']['userName'] | undefined>(testDoc3?.userName);
ExpectType<AutoTypedSchemaType['schema']['description'] | undefined>(testDoc3?.description);

// Model-statics-functions-test
expectType<ReturnType<AutoTypedSchemaType['statics']['staticFn']>>(AutoTypedModel.staticFn());
ExpectType<ReturnType<AutoTypedSchemaType['statics']['staticFn']>>(AutoTypedModel.staticFn());

})();
return AutoTypedModel;
Expand Down Expand Up @@ -155,18 +161,21 @@ function schemaInstanceMethodsAndQueryHelpersOnConnection() {

async function gh15359() {
const res = await conn.bulkWrite([{ model: 'Test', name: 'insertOne', document: { name: 'test1' } }]);
expectType<number>(res.insertedCount);
expectError(res.mongoose.validationErrors);
ExpectType<number>(res.insertedCount);
// @ts-expect-error should not be defined unless option is set
res.mongoose.validationErrors;

const res2 = await conn.bulkWrite([{ model: 'Test', name: 'insertOne', document: { name: 'test2' } }], { ordered: false });
expectType<number>(res2.insertedCount);
expectType<Error[] | undefined>(res2.mongoose?.validationErrors);
ExpectType<number>(res2.insertedCount);
ExpectType<Error[] | undefined>(res2.mongoose?.validationErrors);

const res3 = await conn.bulkWrite([
{ model: 'Test', name: 'updateOne', filter: { name: 'test5' }, update: { $set: { num: 42 } } },
{ model: 'Test', name: 'updateOne', filter: { name: 'test4' }, update: { $set: { num: 'not a number' } } }
], { ordered: false });
expectType<number>(res3.insertedCount);
expectError(res3.validationErrors);
expectType<Error[] | undefined>(res3.mongoose?.validationErrors);
ExpectType<number>(res3.insertedCount);

// @ts-expect-error should not be defined unless option is set
res3.mongoose.validationErrors;
ExpectType<Error[] | undefined>(res3.mongoose?.validationErrors);
}
Loading