mirror of
https://github.com/gosticks/DefinitelyTyped.git
synced 2026-10-05 07:17:04 +00:00
Merge pull request #10790 from simonxca/patch-mongoose
Updates for Mongoose
This commit is contained in:
@@ -11,14 +11,15 @@ import {
|
||||
model,
|
||||
PaginateModel,
|
||||
PaginateOptions,
|
||||
PaginateResult
|
||||
PaginateResult,
|
||||
Document
|
||||
} from 'mongoose';
|
||||
import * as mongoosePaginate from 'mongoose-paginate';
|
||||
import { Router, Request, Response } from 'express';
|
||||
|
||||
|
||||
//#region Test Models
|
||||
interface User {
|
||||
interface User extends Document {
|
||||
email: string;
|
||||
username: string;
|
||||
password: string;
|
||||
@@ -32,8 +33,7 @@ const UserSchema: Schema = new Schema({
|
||||
|
||||
UserSchema.plugin(mongoosePaginate);
|
||||
|
||||
type UserModel<T> = _UserModel<T> & PaginateModel<T>;
|
||||
interface _UserModel<T> {}
|
||||
interface UserModel<T extends Document> extends PaginateModel<T> {};
|
||||
|
||||
let UserModel: UserModel<User> = model<User>('User', UserSchema) as UserModel<User>;
|
||||
//#endregion
|
||||
|
||||
+9
-4
@@ -26,16 +26,21 @@ declare module 'mongoose' {
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
export type PaginateModel<T> = _PaginateModel<T> & Model<T>;
|
||||
interface _PaginateModel<T> {
|
||||
interface PaginateModel<T extends Document> extends Model<T> {
|
||||
paginate(query?: Object, options?: PaginateOptions, callback?: (err: any, result: PaginateResult<T>) => void): Promise<PaginateResult<T>>;
|
||||
}
|
||||
|
||||
export function model<T extends Document, Statics>(
|
||||
export function model<T extends Document>(
|
||||
name: string,
|
||||
schema?: Schema,
|
||||
collection?: string,
|
||||
skipInit?: boolean): Statics & PaginateModel<T>;
|
||||
skipInit?: boolean): PaginateModel<T>;
|
||||
|
||||
export function model<T extends Document, U extends PaginateModel<T>>(
|
||||
name: string,
|
||||
schema?: Schema,
|
||||
collection?: string,
|
||||
skipInit?: boolean): U;
|
||||
}
|
||||
|
||||
declare module 'mongoose-paginate' {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
/// <reference path="mongoose-promise.d.ts" />
|
||||
|
||||
import * as mongoose from 'mongoose';
|
||||
|
||||
var cb = function () {};
|
||||
|
||||
var mongopromise: MongoosePromise<number>;
|
||||
var mongopromise: mongoose.Promise<number>;
|
||||
mongopromise.addBack(function (err, arg) {
|
||||
err.stack;
|
||||
arg.toFixed();
|
||||
@@ -40,7 +42,19 @@ mongopromise.then(function (arg) {
|
||||
});
|
||||
mongopromise.complete();
|
||||
/* static properties */
|
||||
MongoosePromise.ES6(function (complete, error) {
|
||||
mongoose.Promise.ES6(function (complete: any, error: any) {
|
||||
complete.apply(this);
|
||||
error.apply(this);
|
||||
});
|
||||
});
|
||||
/* Practical Examples */
|
||||
interface IUser extends mongoose.Document {
|
||||
name: string;
|
||||
age: number;
|
||||
}
|
||||
var UserSchema = new mongoose.Schema({
|
||||
name: String,
|
||||
age: Number
|
||||
});
|
||||
var UserModel: mongoose.Model<IUser> = mongoose.model<IUser>('Model', UserSchema);
|
||||
UserModel.findOne({}).exec().fulfill();
|
||||
UserModel.find({}).exec().then(() => {}).catch(() => {}).reject('');
|
||||
+115
-116
@@ -3,126 +3,125 @@
|
||||
// Definitions by: simonxca <https://github.com/simonxca/>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
|
||||
/*
|
||||
* These are the default promises included in the Mongoose v4.x
|
||||
* definitions. They will be deprecated beginning Mongoose V5.x
|
||||
* in favor of native ES6 Promises.
|
||||
*
|
||||
* You can switch the promise library that mongoose uses by:
|
||||
*
|
||||
* 1. Including this somewhere in your code:
|
||||
* mongoose.Promise = YOUR_PROMISE;
|
||||
*
|
||||
* 2. Including this somewhere in your main .d.ts file:
|
||||
* type MongoosePromise<T> = YOUR_PROMISE<T>;
|
||||
*/
|
||||
/// <reference path="../mongoose/mongoose.d.ts" />
|
||||
/// <reference path="../mpromise/mpromise.d.ts" />
|
||||
|
||||
/*
|
||||
* http://mongoosejs.com/docs/api.html#promise-js
|
||||
*
|
||||
* Callback signatures are from the mPromise type definitions.
|
||||
* mongoose.d.ts uses global.Promise by default. This is the MongooseJS
|
||||
* mpromise implementation (which are deprecated). If you still want to
|
||||
* use it, install these definitions in your project.
|
||||
*/
|
||||
interface MongoosePromise<T> {
|
||||
/**
|
||||
* Promise constructor.
|
||||
* Promises are returned from executed queries.
|
||||
* @param fn a function which will be called when the promise
|
||||
* is resolved that accepts fn(err, ...){} as signature
|
||||
* @event err Emits when the promise is rejected
|
||||
* @event complete Emits when the promise is fulfilled
|
||||
* @deprecated Mongoose 5.0 will use native promises by default (or bluebird, if native
|
||||
* promises are not present) but still support plugging in your own ES6-compatible
|
||||
* promises library. Mongoose 5.0 will not support mpromise.
|
||||
declare module 'mongoose' {
|
||||
import mpromise = require('mpromise');
|
||||
|
||||
type Promise<T> = MongoosePromise<T>;
|
||||
|
||||
/*
|
||||
* mpromise definitions.
|
||||
* Callback signatures are from the mPromise type definitions.
|
||||
*/
|
||||
new(fn?: (err: any, arg: T) => void): MongoosePromise<T>;
|
||||
new(fn?: (err: any, ...args: T[]) => void): MongoosePromise<T>;
|
||||
class MongoosePromise<T> extends mpromise<T, any> {
|
||||
/**
|
||||
* Promise constructor.
|
||||
* Promises are returned from executed queries.
|
||||
* @param fn a function which will be called when the promise
|
||||
* is resolved that accepts fn(err, ...){} as signature
|
||||
* @event err Emits when the promise is rejected
|
||||
* @event complete Emits when the promise is fulfilled
|
||||
* @deprecated Mongoose 5.0 will use native promises by default (or bluebird, if native
|
||||
* promises are not present) but still support plugging in your own ES6-compatible
|
||||
* promises library. Mongoose 5.0 will not support mpromise.
|
||||
*/
|
||||
constructor(fn?: (err: any, arg: T) => void);
|
||||
constructor(fn?: (err: any, ...args: T[]) => void);
|
||||
|
||||
/**
|
||||
* Adds a single function as a listener to both err and complete.
|
||||
* It will be executed with traditional node.js argument position when the promise is resolved.
|
||||
* @deprecated Use onResolve instead.
|
||||
*/
|
||||
addBack(listener: (err: any, arg: T) => void): this;
|
||||
addBack(listener: (err: any, ...args: T[]) => void): this;
|
||||
|
||||
/**
|
||||
* Adds a listener to the complete (success) event.
|
||||
* @deprecated Adds a listener to the complete (success) event.
|
||||
*/
|
||||
addCallback(listener: (arg: T) => void): this;
|
||||
addCallback(listener: (...args: T[]) => void): this;
|
||||
|
||||
/**
|
||||
* Adds a listener to the err (rejected) event.
|
||||
* @deprecated Use onReject instead.
|
||||
*/
|
||||
addErrback(listener: (err: any) => void): this;
|
||||
|
||||
/** ES6-style .catch() shorthand */
|
||||
catch<TRes>(onReject?: (err: any) => void | TRes | PromiseLike<TRes>): MongoosePromise<TRes>;
|
||||
|
||||
/**
|
||||
* Signifies that this promise was the last in a chain of then()s: if a handler passed
|
||||
* to the call to then which produced this promise throws, the exception will go uncaught.
|
||||
*/
|
||||
end(): void;
|
||||
|
||||
/**
|
||||
* Rejects this promise with err.
|
||||
* If the promise has already been fulfilled or rejected, not action is taken.
|
||||
* Differs from #reject by first casting err to an Error if it is not instanceof Error.
|
||||
*/
|
||||
error(err: any): this;
|
||||
|
||||
/**
|
||||
* Adds listener to the event.
|
||||
* If event is either the success or failure event and the event has already been emitted,
|
||||
* thelistener is called immediately and passed the results of the original emitted event.
|
||||
*/
|
||||
on(event: string, listener: Function): this;
|
||||
|
||||
/**
|
||||
* Rejects this promise with reason.
|
||||
* If the promise has already been fulfilled or rejected, not action is taken.
|
||||
*/
|
||||
reject(reason: Object | string | Error): this;
|
||||
|
||||
/**
|
||||
* Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed.
|
||||
* If the promise has already been fulfilled or rejected, not action is taken.
|
||||
* err will be cast to an Error if not already instanceof Error.
|
||||
* NOTE: overrides mpromise#resolve to provide error casting.
|
||||
* @param err error or null
|
||||
* @param val value to fulfill the promise with
|
||||
*/
|
||||
resolve(err?: any, val?: Object): this;
|
||||
|
||||
/**
|
||||
* Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as
|
||||
* SUCCESS/ERROR callbacks to this promise after the nextTick.
|
||||
* Conforms to promises/A+ specification.
|
||||
*/
|
||||
then<TRes>(onFulFill: (arg: T) => void | TRes | PromiseLike<TRes>,
|
||||
onReject?: (err: any) => void | TRes | PromiseLike<TRes>): MongoosePromise<TRes>;
|
||||
then<TRes>(onFulfill: (...args: T[]) => void | TRes | PromiseLike<TRes>,
|
||||
onReject?: (err: any) => void | TRes | PromiseLike<TRes>): MongoosePromise<TRes>;
|
||||
|
||||
/**
|
||||
* Fulfills this promise with passed arguments. Alias of mpromise#fulfill.
|
||||
* @deprecated Use fulfill instead.
|
||||
*/
|
||||
complete(args: T): this;
|
||||
complete(...args: T[]): this;
|
||||
|
||||
/** Fulfills this promise with passed arguments. */
|
||||
fulfill(...args: T[]): this;
|
||||
fulfill(arg: T): this;
|
||||
|
||||
/** ES6-style promise constructor wrapper around mpromise. */
|
||||
static ES6<TRes>(resolver: (
|
||||
complete: (...args: TRes[]) => void | TRes | PromiseLike<TRes>,
|
||||
error: (e: any) => void | TRes | PromiseLike<TRes>
|
||||
) => void): MongoosePromise<TRes>;
|
||||
}
|
||||
}
|
||||
|
||||
declare class MongoosePromise<T> {
|
||||
/**
|
||||
* Adds a single function as a listener to both err and complete.
|
||||
* It will be executed with traditional node.js argument position when the promise is resolved.
|
||||
* @deprecated Use onResolve instead.
|
||||
*/
|
||||
addBack(listener: (err: any, arg: T) => void): this;
|
||||
addBack(listener: (err: any, ...args: T[]) => void): this;
|
||||
|
||||
/**
|
||||
* Adds a listener to the complete (success) event.
|
||||
* @deprecated Adds a listener to the complete (success) event.
|
||||
*/
|
||||
addCallback(listener: (arg: T) => void): this;
|
||||
addCallback(listener: (...args: T[]) => void): this;
|
||||
|
||||
/**
|
||||
* Adds a listener to the err (rejected) event.
|
||||
* @deprecated Use onReject instead.
|
||||
*/
|
||||
addErrback(listener: (err: any) => void): this;
|
||||
|
||||
/** ES6-style .catch() shorthand */
|
||||
catch<TRes>(onReject?: (err: any) => void | TRes | PromiseLike<TRes>): MongoosePromise<TRes>;
|
||||
|
||||
/**
|
||||
* Signifies that this promise was the last in a chain of then()s: if a handler passed
|
||||
* to the call to then which produced this promise throws, the exception will go uncaught.
|
||||
*/
|
||||
end(): void;
|
||||
|
||||
/**
|
||||
* Rejects this promise with err.
|
||||
* If the promise has already been fulfilled or rejected, not action is taken.
|
||||
* Differs from #reject by first casting err to an Error if it is not instanceof Error.
|
||||
*/
|
||||
error(err: any): this;
|
||||
|
||||
/**
|
||||
* Adds listener to the event.
|
||||
* If event is either the success or failure event and the event has already been emitted,
|
||||
* thelistener is called immediately and passed the results of the original emitted event.
|
||||
*/
|
||||
on(event: string, listener: Function): this;
|
||||
|
||||
/**
|
||||
* Rejects this promise with reason.
|
||||
* If the promise has already been fulfilled or rejected, not action is taken.
|
||||
*/
|
||||
reject(reason: Object | string | Error): this;
|
||||
|
||||
/**
|
||||
* Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed.
|
||||
* If the promise has already been fulfilled or rejected, not action is taken.
|
||||
* err will be cast to an Error if not already instanceof Error.
|
||||
* NOTE: overrides mpromise#resolve to provide error casting.
|
||||
* @param err error or null
|
||||
* @param val value to fulfill the promise with
|
||||
*/
|
||||
resolve(err?: any, val?: Object): this;
|
||||
|
||||
/**
|
||||
* Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as
|
||||
* SUCCESS/ERROR callbacks to this promise after the nextTick.
|
||||
* Conforms to promises/A+ specification.
|
||||
*/
|
||||
then<TRes>(onFulFill: (arg: T) => void | TRes | PromiseLike<TRes>,
|
||||
onReject?: (err: any) => void | TRes | PromiseLike<TRes>): MongoosePromise<TRes>;
|
||||
then<TRes>(onFulfill: (...args: T[]) => void | TRes | PromiseLike<TRes>,
|
||||
onReject?: (err: any) => void | TRes | PromiseLike<TRes>): MongoosePromise<TRes>;
|
||||
|
||||
/**
|
||||
* Fulfills this promise with passed arguments. Alias of mpromise#fulfill.
|
||||
* @deprecated Use fulfill instead.
|
||||
*/
|
||||
complete(args: T): this;
|
||||
complete(...args: T[]): this;
|
||||
|
||||
/** Fulfills this promise with passed arguments. */
|
||||
fulfill(...args: T[]): this;
|
||||
fulfill(arg: T): this;
|
||||
|
||||
/** ES6-style promise constructor wrapper around mpromise. */
|
||||
static ES6<TRes>(resolver: (
|
||||
complete: (...args: TRes[]) => void | TRes | PromiseLike<TRes>,
|
||||
error: (e: any) => void | TRes | PromiseLike<TRes>
|
||||
) => void): MongoosePromise<TRes>;
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
## MongooseJS Typescript Docs
|
||||
Below are some examples of how to use these Definitions.<br>
|
||||
Scenarios where the Typescript code is identical to plain Javascript code are omitted.
|
||||
|
||||
### Table of Contents
|
||||
* [Mongoose Methods, Properties, Constructors](#mongoose-methods-properties-constructors)
|
||||
* [Creating and Saving Documents](#creating-and-saving-documents)
|
||||
* [Instance Methods, Virtual Properties](#instance-methods-and-virtual-properties)
|
||||
* [Static Methods](#static-methods)
|
||||
* [Plugins](#plugins)
|
||||
* [Promises](#promises)
|
||||
* [FAQ](#faq)
|
||||
|
||||
#### Mongoose Methods, Properties, Constructors
|
||||
You can call methods from the mongoose instance using:
|
||||
```
|
||||
import * as mongoose from 'mongoose';
|
||||
var MyModel = mongoose.model(...);
|
||||
var MySchema: mongoose.Schema = new mongoose.Schema(...);
|
||||
```
|
||||
|
||||
Alternatively, you can import individual names and call them:
|
||||
```
|
||||
import {model, Schema} from 'mongoose';
|
||||
var MyModel = model(...);
|
||||
var MySchema: Schema = new Schema(...):
|
||||
```
|
||||
[top](#mongoosejs-typescript-docs)
|
||||
|
||||
#### Creating and Saving Documents
|
||||
```
|
||||
import {Document, model, Model, Schema} from 'mongoose';
|
||||
|
||||
var UserSchema: Schema = new Schema({
|
||||
username: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true
|
||||
},
|
||||
age: Number,
|
||||
friends: [String],
|
||||
data: [Schema.Types.Mixed]
|
||||
});
|
||||
|
||||
interface IUser extends Document {
|
||||
username: string;
|
||||
age: number;
|
||||
friends: string[];
|
||||
data: any[];
|
||||
}
|
||||
|
||||
var UserModel: Model<IUser> = mongoose.model<IUser>('User', UserSchema);
|
||||
|
||||
var user = new UserModel({name: 'Jane'});
|
||||
user.username; // IUser properties are available
|
||||
user.save(); // mongoose Document methods are available
|
||||
|
||||
UserModel.findOne({}, (err: any, user: IUser) => {
|
||||
user.username; // IUser properties are available
|
||||
user.save(); // mongoose Document methods are available
|
||||
});
|
||||
```
|
||||
[top](#mongoosejs-typescript-docs)
|
||||
|
||||
#### Instance Methods and Virtual Properties
|
||||
```
|
||||
import {Document, model, Model, Schema} from 'mongoose';
|
||||
|
||||
var UserSchema: Schema = new Schema({
|
||||
name: String
|
||||
});
|
||||
|
||||
UserSchema.methods.method1 = function () { return '' };
|
||||
UserSchema.virtual('nameInCaps').get(function () {
|
||||
return this.name.toUpperCase();
|
||||
});
|
||||
UserSchema.virtual('nameInCaps').set(function (caps) {
|
||||
this.name = caps.toLowerCase();
|
||||
});
|
||||
|
||||
interface IUser extends Document {
|
||||
name: string;
|
||||
nameInCaps: string;
|
||||
method1: () => string;
|
||||
}
|
||||
|
||||
var UserModel: Model<IUser> = model<IUser>('User', UserSchema);
|
||||
var user = new UserModel({name: 'Billy'});
|
||||
|
||||
user.method1(); // IUser methods are available
|
||||
user.nameInCaps; // virtual properties can be used
|
||||
|
||||
UserModel.findOne({}, (err: any, user: IUser) => {
|
||||
user.method1(); // IUser methods are available
|
||||
user.nameInCaps; // virtual properties can be used
|
||||
});
|
||||
```
|
||||
[top](#mongoosejs-typescript-docs)
|
||||
|
||||
#### Static Methods
|
||||
```
|
||||
import {Document, model, Model, Schema} from 'mongoose';
|
||||
|
||||
var UserSchema = new Schema({});
|
||||
UserSchema.statics.static1 = function () { return '' };
|
||||
|
||||
interface IUserDocument extends Document {...}
|
||||
interface IUserModel extends Model<IUserDocument> {
|
||||
static1: () => string;
|
||||
}
|
||||
|
||||
var UserModel: IUserModel = model<IUser, IUserModel>('User', UserSchema);
|
||||
UserModel.static1(); // static methods are available
|
||||
```
|
||||
[top](#mongoosejs-typescript-docs)
|
||||
|
||||
#### Plugins
|
||||
To write definitions for plugins, extend the mongoose module and create a simple plugin module:
|
||||
```
|
||||
// plugin.d.ts
|
||||
declare module 'mongoose' {
|
||||
export interface PassportLocalDocument {...}
|
||||
export interface PassportLocalSchema extends Schema {...}
|
||||
export interface PassportLocalModel<T extends PassportLocalDocument> extends Model<T> {...}
|
||||
...
|
||||
}
|
||||
|
||||
declare module 'passport-local-mongoose' {
|
||||
import mongoose = require('mongoose');
|
||||
var _: (schema: mongoose.Schema, options?: Object) => void;
|
||||
export = _;
|
||||
}
|
||||
|
||||
// user.ts
|
||||
import {
|
||||
model,
|
||||
PassportLocalDocument,
|
||||
PassportLocalSchema,
|
||||
PassportLocalModel
|
||||
Schema
|
||||
} from 'mongoose';
|
||||
import * as passportLocalMongoose from 'passport-local-mongoose';
|
||||
|
||||
var UserSchema: PassportLocalSchema = new Schema({});
|
||||
UserSchema.plugin(passportLocalMongoose, options);
|
||||
|
||||
interface IUser extends PassportLocalDocument {...}
|
||||
interface IUserModel<T extends PassportLocalDocument> extends PassportLocalModel<T> {...}
|
||||
|
||||
var UserModel: IUserModel<IUser> = model<IUser>('User', UserSchema);
|
||||
```
|
||||
Full example for [Passport Local Mongoose](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/passport-local-mongoose/passport-local-mongoose.d.ts)<br>
|
||||
[top](#mongoosejs-typescript-docs)
|
||||
|
||||
#### Promises
|
||||
These definitions use global.Promise by default. If you would like to use mongoose's own mpromise
|
||||
definition (which is deprecated), you can install definitions for [mongoose-promise](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/mongoose-promise).
|
||||
|
||||
If you'd like to use something other than global.Promise, you'll need to create a simple .d.ts file:
|
||||
```
|
||||
// promise-bluebird.d.ts
|
||||
import * as Bluebird from 'bluebird';
|
||||
|
||||
declare module 'mongoose' {
|
||||
type Promise<T> = Bluebird<T>;
|
||||
}
|
||||
|
||||
// promise-q.d.ts
|
||||
import * as Q from 'q';
|
||||
|
||||
declare module 'mongoose' {
|
||||
type Promise<T> = Q.Promise<T>;
|
||||
}
|
||||
|
||||
// another-promise.d.ts
|
||||
...
|
||||
```
|
||||
To use it, you will need to `/// <reference path="promise-bluebird.d.ts" />` in one of your source code files,
|
||||
or include the `.d.ts` file in your compile.
|
||||
|
||||
To assign the new promise library in your code, you will need to use one of the following options (since
|
||||
Typescript does not allow assigning properties of imported modules):
|
||||
|
||||
* `(<any>mongoose).Promise = YOUR_PROMISE;`
|
||||
* `require('mongoose').Promise = YOUR_PROMISE;`
|
||||
* `import mongoose = require('mongoose'); ... mongoose.Promise = YOUR_PROMISE;`
|
||||
|
||||
[top](#mongoosejs-typescript-docs)
|
||||
|
||||
#### FAQ
|
||||
Q: Why are there 2 interfaces for Documents called Document and MongooseDocument?<br>
|
||||
A: People have been using this for a long time:
|
||||
```
|
||||
interface IUser extends mongoose.Document {
|
||||
...
|
||||
}
|
||||
```
|
||||
When it should really be this:
|
||||
```
|
||||
interface IUser extends mongoose.model {
|
||||
...
|
||||
}
|
||||
```
|
||||
For backwards compatibility Document is an interface for [mongoose.model](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)<br>
|
||||
And MongooseDocument is an interface for [mongoose.Document](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)<br>
|
||||
At some point in the future this may get fixed, which would require fixing your code.
|
||||
<br>
|
||||
[top](#mongoosejs-typescript-docs)
|
||||
+59
-25
@@ -27,7 +27,7 @@ mongoose.connect(connectUri, {
|
||||
autoIndex: true
|
||||
},
|
||||
mongos: true
|
||||
}).then(cb).fulfill();
|
||||
}).then(cb);
|
||||
mongoose.connect(connectUri, function (error) {
|
||||
error.stack;
|
||||
});
|
||||
@@ -45,14 +45,14 @@ mongoose.createConnection('localhost', 'database', 3000, {
|
||||
autoIndex: false
|
||||
}
|
||||
}).open('');
|
||||
mongoose.disconnect(cb).then(cb).fulfill;
|
||||
mongoose.disconnect(cb).then(cb);
|
||||
mongoose.get('test');
|
||||
mongoose.model('Actor', new mongoose.Schema({
|
||||
name: String
|
||||
}), 'collectionName', true).find({});
|
||||
mongoose.model('Actor').find({});
|
||||
mongoose.modelNames()[0].toLowerCase();
|
||||
new (new mongoose.Mongoose()).Mongoose().connect('');
|
||||
new (new mongoose.Mongoose(9, 8, 7)).Mongoose(1, 2, 3).connect('');
|
||||
mongoose.plugin(cb, {}).connect('');
|
||||
mongoose.set('test', 'value');
|
||||
mongoose.set('debug', function(collectionName: any, methodName: any, arg1: any, arg2: any) {});
|
||||
@@ -136,7 +136,6 @@ conn1.model('myModel', new mongoose.Schema({}), 'myCol').find();
|
||||
interface IStatics {
|
||||
staticMethod1: (a: number) => string;
|
||||
}
|
||||
conn1.model<{}, IStatics>('').staticMethod1;
|
||||
conn1.modelNames()[0].toLowerCase();
|
||||
conn1.config.hasOwnProperty('');
|
||||
conn1.db.bufferMaxEntries;
|
||||
@@ -350,7 +349,7 @@ new mongoose.Schema({
|
||||
* section document.js
|
||||
* http://mongoosejs.com/docs/api.html#document-js
|
||||
*/
|
||||
var doc: mongoose.Document;
|
||||
var doc: mongoose.MongooseDocument;
|
||||
doc.$isDefault('path').valueOf();
|
||||
doc.depopulate('path');
|
||||
doc.equals(doc).valueOf();
|
||||
@@ -465,7 +464,7 @@ mongooseArray.length;
|
||||
* http://mongoosejs.com/docs/api.html#types-documentarray-js
|
||||
*/
|
||||
// The constructor is private api, but we'll use it to test
|
||||
var documentArray: mongoose.Types.DocumentArray<mongoose.Document> =
|
||||
var documentArray: mongoose.Types.DocumentArray<mongoose.MongooseDocument> =
|
||||
new mongoose.Types.DocumentArray();
|
||||
documentArray.create({}).errors;
|
||||
documentArray.id(new Buffer('hi'));
|
||||
@@ -500,7 +499,7 @@ var objectId: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexStr
|
||||
objectId = new mongoose.Types.ObjectId(12345);
|
||||
objectId.getTimestamp();
|
||||
/* practical examples */
|
||||
export interface IManagerSchema extends mongoose.Document {
|
||||
export interface IManagerSchema extends mongoose.MongooseDocument {
|
||||
user: mongoose.Schema.Types.ObjectId;
|
||||
}
|
||||
export var ManagerSchema = new mongoose.Schema({
|
||||
@@ -530,7 +529,7 @@ embeddedDocument.execPopulate();
|
||||
* section query.js
|
||||
* http://mongoosejs.com/docs/api.html#query-js
|
||||
*/
|
||||
var query: mongoose.Query<mongoose.Document[]>;
|
||||
var query: mongoose.Query<mongoose.MongooseDocument[]>;
|
||||
query.$where('').$where(cb);
|
||||
query.all(99).all('path', 99);
|
||||
query.and([{ color: 'green' }, { status: 'ok' }]).and([]);
|
||||
@@ -541,7 +540,7 @@ query.where('loc').within().box(lowerLeft, upperRight)
|
||||
query.box({ ll : lowerLeft, ur : upperRight }).box({});
|
||||
var queryModel = mongoose.model('QModel')
|
||||
query.cast(new queryModel(), {}).hasOwnProperty('');
|
||||
query.catch(function (err) {}).catch();
|
||||
query.catch(cb).catch(cb);
|
||||
query.center({}).center({});
|
||||
query.centerSphere({ center: [50, 50], radius: 10 }).centerSphere('path', {});
|
||||
query.circle({ center: [50, 50], radius: 10 }).circle('path');
|
||||
@@ -696,7 +695,7 @@ query.stream().on('data', function (doc: any) {
|
||||
});
|
||||
query.tailable().tailable(false);
|
||||
query.then(cb).catch(cb);
|
||||
(new (query.toConstructor())()).toConstructor();
|
||||
(new (query.toConstructor())(1, 2, 3)).toConstructor();
|
||||
query.update({}, doc, {
|
||||
|
||||
}, cb);
|
||||
@@ -761,8 +760,9 @@ schemaArray.sparse(true);
|
||||
* section schema/string.js
|
||||
* http://mongoosejs.com/docs/api.html#schema-string-js
|
||||
*/
|
||||
var MongoDocument: mongoose.Document;
|
||||
var schemastring: mongoose.Schema.Types.String = new mongoose.Schema.Types.String('hello');
|
||||
schemastring.checkRequired(234, new mongoose.Document()).valueOf();
|
||||
schemastring.checkRequired(234, MongoDocument).valueOf();
|
||||
schemastring.enum(['hi', 'a', 'b']).enum('hi').enum({});
|
||||
schemastring.lowercase().lowercase();
|
||||
schemastring.match(/re/, 'error').match(/re/);
|
||||
@@ -790,7 +790,7 @@ documentarray.sparse(true);
|
||||
* http://mongoosejs.com/docs/api.html#schema-number-js
|
||||
*/
|
||||
var schemanumber: mongoose.Schema.Types.Number = new mongoose.Schema.Types.Number('num', {});
|
||||
schemanumber.checkRequired(999, new mongoose.Document()).valueOf();
|
||||
schemanumber.checkRequired(999, MongoDocument).valueOf();
|
||||
schemanumber.max(999, 'error').max(999);
|
||||
schemanumber.min(999, 'error').min(999);
|
||||
/* static properties */
|
||||
@@ -803,7 +803,7 @@ schemanumber.sparse(true);
|
||||
* http://mongoosejs.com/docs/api.html#schema-date-js
|
||||
*/
|
||||
var schemadate: mongoose.Schema.Types.Date = new mongoose.Schema.Types.Date('99');
|
||||
schemadate.checkRequired([], new mongoose.Document()).valueOf();
|
||||
schemadate.checkRequired([], MongoDocument).valueOf();
|
||||
schemadate.expires(99).expires('now');
|
||||
schemadate.max(new Date(), 'error').max(new Date(''));
|
||||
schemadate.min(new Date(), 'error').min(new Date(''));
|
||||
@@ -817,7 +817,7 @@ schemadate.sparse(true);
|
||||
* http://mongoosejs.com/docs/api.html#schema-buffer-js
|
||||
*/
|
||||
var schemabuffer: mongoose.Schema.Types.Buffer = new mongoose.Schema.Types.Buffer('99');
|
||||
schemabuffer.checkRequired(999, new mongoose.Document()).valueOf();
|
||||
schemabuffer.checkRequired(999, MongoDocument).valueOf();
|
||||
/* static properties */
|
||||
mongoose.Schema.Types.Buffer.schemaName.toLowerCase();
|
||||
/* inherited properties */
|
||||
@@ -840,7 +840,7 @@ schemaboolean.sparse(true);
|
||||
*/
|
||||
var schemaobjectid: mongoose.Schema.Types.ObjectId = new mongoose.Schema.Types.ObjectId('99');
|
||||
schemaobjectid.auto(true).auto(false);
|
||||
schemaobjectid.checkRequired(99, new mongoose.Document()).valueOf();
|
||||
schemaobjectid.checkRequired(99, MongoDocument).valueOf();
|
||||
/* static properties */
|
||||
mongoose.Schema.Types.ObjectId.schemaName.toLowerCase();
|
||||
/* inherited properties */
|
||||
@@ -1060,12 +1060,13 @@ mongoose.model('').aggregate()
|
||||
});
|
||||
|
||||
/* pluggable promise */
|
||||
mongoose.Promise = Promise;
|
||||
(<any>mongoose).Promise = Promise;
|
||||
require('mongoose').Promise = Promise;
|
||||
mongoose.Promise.race;
|
||||
mongoose.Promise.all;
|
||||
|
||||
mongoose.model('').findOne()
|
||||
.exec().addErrback(cb);
|
||||
.exec().then(cb);
|
||||
|
||||
/*
|
||||
* section model.js
|
||||
@@ -1078,8 +1079,9 @@ var MongoModel = mongoose.model('MongoModel', new mongoose.Schema({
|
||||
required: true
|
||||
}
|
||||
}), 'myCollection', true);
|
||||
MongoModel.$where('indexOf("val") !== -1').exec(function (err, docs) {
|
||||
MongoModel.find({}).$where('indexOf("val") !== -1').exec(function (err, docs) {
|
||||
docs[0].save();
|
||||
docs[0].__v;
|
||||
});
|
||||
MongoModel.findById(999, function (err, doc) {
|
||||
doc.increment();
|
||||
@@ -1249,6 +1251,10 @@ mongoModel.discriminators;
|
||||
mongoModel.modelName.toLowerCase();
|
||||
MongoModel = mongoModel.base.model('new', mongoModel.schema);
|
||||
/* inherited properties */
|
||||
MongoModel.modelName;
|
||||
mongoModel.modelName;
|
||||
MongoModel.collection;
|
||||
mongoModel.collection;
|
||||
mongoModel._id;
|
||||
mongoModel.execPopulate();
|
||||
mongoModel.on('data', cb);
|
||||
@@ -1310,7 +1316,7 @@ LocModel.find()
|
||||
});
|
||||
});
|
||||
});
|
||||
LocModel.$where('')
|
||||
LocModel.find({}).$where('')
|
||||
.exec(function (err, locations) {
|
||||
locations[0].name;
|
||||
locations[1].openingTimes;
|
||||
@@ -1346,10 +1352,38 @@ LocModel.geoSearch({}, {
|
||||
interface IStatics {
|
||||
staticMethod2: (a: number) => string;
|
||||
}
|
||||
var StaticModel = mongoose.model<Location, IStatics>('Location');
|
||||
StaticModel.staticMethod2(9).toUpperCase();
|
||||
(new StaticModel()).save(function (err, doc) {
|
||||
doc.openingTimes;
|
||||
doc.model<Location, IStatics>('').staticMethod2;
|
||||
interface MyDocument extends mongoose.Document {
|
||||
prop: string;
|
||||
method: () => void;
|
||||
}
|
||||
interface MyModel extends mongoose.Model<MyDocument> {
|
||||
staticProp: string;
|
||||
staticMethod: () => void;
|
||||
}
|
||||
interface ModelStruct {
|
||||
doc: MyDocument;
|
||||
model: MyModel;
|
||||
method1: (callback: (model: MyModel, doc: MyDocument) => void) => MyModel;
|
||||
}
|
||||
var modelStruct1: ModelStruct;
|
||||
var myModel1: MyModel;
|
||||
var myDocument1: MyDocument;
|
||||
modelStruct1.method1(function (myModel1, myDocument1) {
|
||||
myModel1.staticProp;
|
||||
myModel1.staticMethod();
|
||||
myDocument1.prop;
|
||||
myDocument1.method();
|
||||
}).staticProp.toLowerCase();
|
||||
var mySchema = new mongoose.Schema({});
|
||||
export var Final: MyModel = <MyModel>mongoose.connection.model<MyDocument>('Final', mySchema);
|
||||
Final.findOne(function (err: any, doc: MyDocument) {
|
||||
doc.save();
|
||||
doc.remove();
|
||||
doc.model('');
|
||||
});
|
||||
StaticModel.model<Location, IStatics>('').staticMethod2;
|
||||
export var Final2: MyModel = mongoose.model<MyDocument, MyModel>('Final2', mySchema);
|
||||
Final2.staticMethod();
|
||||
Final2.staticProp;
|
||||
var final2 = new Final2();
|
||||
final2.prop;
|
||||
final2.method;
|
||||
Vendored
+2264
-2358
File diff suppressed because it is too large
Load Diff
@@ -11,6 +11,7 @@
|
||||
import {
|
||||
Schema,
|
||||
model,
|
||||
Document,
|
||||
PassportLocalDocument,
|
||||
PassportLocalSchema,
|
||||
PassportLocalModel,
|
||||
@@ -34,7 +35,7 @@ interface User extends PassportLocalDocument {
|
||||
last: Date;
|
||||
}
|
||||
|
||||
const UserSchema: PassportLocalSchema = <PassportLocalSchema>new Schema({
|
||||
const UserSchema: PassportLocalSchema = new Schema({
|
||||
username: String,
|
||||
hash: String,
|
||||
salt: String,
|
||||
@@ -77,10 +78,9 @@ options.errorMessages = errorMessages;
|
||||
|
||||
UserSchema.plugin(passportLocalMongoose, options);
|
||||
|
||||
type UserModel<T extends PassportLocalDocument> = _UserModel<T> & PassportLocalModel<T>;
|
||||
interface _UserModel<T extends PassportLocalDocument> {}
|
||||
interface UserModel<T extends Document> extends PassportLocalModel<T> {}
|
||||
|
||||
let UserModel: UserModel<User> = model<User>('User', UserSchema) as UserModel<User>;
|
||||
let UserModel: UserModel<User> = model<User>('User', UserSchema);
|
||||
//#endregion
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ passport.use('login', new LocalStrategy({
|
||||
process.nextTick(() => {
|
||||
UserModel
|
||||
.findOne({ 'username': username })
|
||||
.exec((err: any, user: model<User>) => {
|
||||
.exec((err: any, user: User) => {
|
||||
if (err) {
|
||||
console.log(err);
|
||||
return done(err, null);
|
||||
|
||||
+10
-5
@@ -10,14 +10,13 @@ declare module 'mongoose' {
|
||||
import passportLocal = require('passport-local');
|
||||
|
||||
// methods
|
||||
export interface PassportLocalDocument {
|
||||
export interface PassportLocalDocument extends Document {
|
||||
setPassword(password: string, cb: (err: any, res: any) => void): void;
|
||||
authenticate(password: string, cb: (err: any, res: any, error: any) => void): void;
|
||||
}
|
||||
|
||||
// statics
|
||||
export type PassportLocalModel<T extends PassportLocalDocument> = _PassportLocalModel<T> & Model<T>;
|
||||
interface _PassportLocalModel<T extends PassportLocalDocument> {
|
||||
interface PassportLocalModel<T extends Document> extends Model<T> {
|
||||
authenticate(): (username: string, password: string, cb: (err: any, res: T, error: any) => void) => void;
|
||||
serializeUser(): (user: PassportLocalModel<T>, cb: (err: any) => void) => void;
|
||||
deserializeUser(): (username: string, cb: (err: any) => void) => void;
|
||||
@@ -77,11 +76,17 @@ declare module 'mongoose' {
|
||||
): this;
|
||||
}
|
||||
|
||||
export function model<T extends PassportLocalDocument, Statics>(
|
||||
export function model<T extends Document>(
|
||||
name: string,
|
||||
schema?: PassportLocalSchema,
|
||||
collection?: string,
|
||||
skipInit?: boolean): Statics & PassportLocalModel<T>;
|
||||
skipInit?: boolean): PassportLocalModel<T>;
|
||||
|
||||
export function model<T extends Document, U extends PassportLocalModel<T>>(
|
||||
name: string,
|
||||
schema?: PassportLocalSchema,
|
||||
collection?: string,
|
||||
skipInit?: boolean): U;
|
||||
}
|
||||
|
||||
declare module 'passport-local-mongoose' {
|
||||
|
||||
Reference in New Issue
Block a user