DefinitelyTyped/mongoose
Andy c968762595 Merge 'master' to 'types-2.0' one last time (#13277)
* Added missing nconf.required(keys) and Provider.required(keys) methods.

* update to 4.7.0, add querycursor.map() and schema.loadClass()

* add error callback for schema.post()

* Added playsInline property as introduced in React 15.3.2

* Add definitions for redux-localstorage and main enhancers (#12580)

* Add definitions for redux-localstorage

* Add definitions for redux-localstorage-filter enhancer

* Add definitions for redux-localstorage-debounce enhancer

* csurf.d.ts relying on CookieOptions from express

It seems express no longer exports `CookieOptions`, we need to import `express-serve-static-core` instead.

* Added height property to IDialogOptions

* versionKey type

* kendo-ui: mark toString() params as optional (#13164)

These function parameters are optional according to the upstream
docs, e.g.
  http://docs.telerik.com/kendo-ui/api/javascript/geometry/matrix#methods-toString

* Ensure that zoneAbbr and zoneName are expected type (string).

* Update moment-timezone.d.ts

* Fix syntax error in interact.d.ts

A parameter name was missing making TypeScript compiler fail.

* adding type for move to fs-extra

* fixing signature of sinon/alwaysReturned based on the http://sinonjs.org/docs/#sinonspy

* increasing version number

* returning back the version number to the origin number

* reversing changes in fs-extra

* Request that PRs have meaningful titles

* Improvement to existing nouislider type definition. (#12033)

* updated nouislider version and added a lot of tests out of the documentation

* corrected intentation

* corrected untyped variables, issue raised by Travis

* incorporated feedback on pull request

* #13037 (#13039)

* #13037

* pointToLayer first argument type fixed
GeoJSON.Point to GeoJSON.Feature<GeoJSON.Point>

* Missing cc in sendgrid packate (#13063)

The sendgrid package was missing the `cc` field, and the `bcc` field had a too generic type (`any` instead of `string[]`, as used on the `setCcs` and `setBccs` below.

* Fixes #12414 (#13076)

* Fixes #12414

* Make applicationServerKey optional

* added ariaLabelledBy and ariaDescribedBy to IModalSettings (#13004)

* Ceymard leaflet (#13007)

* replaced all overrides of LatLng by a single use of LatLngExpression when appropriate

* Changed Point, PointTuple overrides to use PointExpression instead

* Changet use of LatLngBounds and Bounds in general to use the Expression variant instead of having several overrides

* add ElasticSeach 5.x API function for deleteByQuery (#13014)

* add ElasticSeach 5.x API function for deleteByQuery

* use searchParams for deleteByQuery, as theses resemble the documentation.

* add DeleteByQueryParams parameter type.

* add deleteByQuery to tests.

* Make `less` render options optional (#13078)

* Added semver

* Updated gravity definition. (#13088)

* Full Redis client options (#13108)

* Added missing return type to on() methods. (#13082)

* Update react-native.0.29.d.ts (#13118)

drawerPosition is of type `number`
Android DrawerConsts.DrawerPosition.Left is equivalent to DrawerLayoutAndroid.positions.Left
Android DrawerConsts.DrawerPosition.Right is equivalent to DrawerLayoutAndroid.positions.Right

* Upgrade to match braintree-web 3.6.1 (#13098)

* Update to match braintree-web version 3.3.0

* Upgrade to match Braintree-web v3.5.0

* upgrade to match braintree-web 3.6.1

add US bank class

* Fix missing parameters from svg append (#13119)

* Add parameter declarations to append()

* Made insertFirst parameter optional

* Correct missing ‘auto’ option of GridList’s cellHeight (#13094)

* Add new Angular 1.5.9 methods to $compileProvider  (#13096)

* Add new Angular 1.5.9 methods to $compileProvider

Add new methods available in Angular 1.5.9: onChangesTtl(), commentDirectivesEnabled() and cssClassDirectivesEnabled()

* Add JSDoc to Angular 1.59 new methods of $compileProvider

JSDoc for onChangesTtl(), commentDirectivesEnabled() and cssClassDirectivesEnabled() methods.

* Expand $compileProvider JSDoc

Urls added to JSDoc of Angular 1.5.9 new methods .

* Changed type of injectedScript property to string (#13120)

The injectedScript property should take string value with script code, not the bool flag as in current version

* Use unions for openlayers string enums (#13134)

* Update google.maps.MapPane interface (#13122)

* Removing myself (AlStar01) as definition author from angular-material.d.ts (#13125)

* Clarify that notNeededPackages.json is just for packages formerly on DefinitelyTyped (#13156)

* Update Parsimmon typings (#13146)

* Update AmCharts.d.ts (#13170)

* knex: add MySqlConnectionConfig, tests (#13161)

* knex: add MySqlConnectionConfig, tests

* knex: add types for MySqlConnectionConfig queryFormat params

* Add note in readme about tsjs-lib-generator (#13210)

* Remove redux-localstorage packages; added by #13115 instead
2016-12-12 11:00:28 -08:00
..
index.d.ts fix SchemaOptions.versionKey type 2016-12-08 16:41:41 +00:00
mongoose-3.x-tests.ts
mongoose-3.x.d.ts Merge 10/04 (#11739) 2016-10-05 11:40:00 -07:00
mongoose-tests.ts Merge 'master' to 'types-2.0' one last time (#13277) 2016-12-12 11:00:28 -08:00
README.md Merge master into typings-2.0 2016-11-29 16:51:33 -08:00
tsconfig.json

MongooseJS Typescript Docs

Below are some examples of how to use these Definitions.
Scenarios where the Typescript code is identical to plain Javascript code are omitted.

Table of Contents

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

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> = 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

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.

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

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;
  method1: () => string;
  nameInCaps: 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

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

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
top

FAQ and Common Mistakes

Q: When to use mongoose.Schema.Types.ObjectId and mongoose.Types.ObjectId
When creating schemas in code use mongoose.Schema.Types.ObjectId:

var UserSchema = new mongoose.Schema({
  id: mongoose.Schema.Types.ObjectId
});

Mongoose uses mongoose.Schema.Types.ObjectId internally to create the schema. However, if you define your interface like this:

interface IUser extends mongoose.Document {
  id: mongoose.Schema.Types.ObjectId;
}
...
user.id = new mongoose.Types.ObjectId();

To use it, you will need to /// <reference path="promise-bluebird.d.ts" /> in one of your source code files,

To assign the new promise library in your code, you will need to use one of the following options (since interface IUser extends mongoose.Document { id: mongoose.Types.ObjectId; // for type-checking, doesn't affect code behaviour }

var UserSchema = new UserSchema({ id: mongoose.Schema.Types.ObjectId; // for creating the schema only });

var User = mongoose.model('User', UserSchema); var user = new User({}); user.id = new mongoose.Types.ObjectId();

[top](#mongoosejs-typescript-docs)

**Q: Why are there 2 interfaces for Documents called Document and MongooseDocument?**<br>
People have been using this for a long time:
```typescript
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
And MongooseDocument is an interface for mongoose.Document
At some point in the future this may get fixed, which would require fixing your code.
top