Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Promise with bluebird and typescript

I am developing an application with nodejs/typescript and a mongodb database. To query the database, I am using mongoose.

I've just read an article from the mongoose documentation on how to plug in an external promise library and it is very simple:

import mongoose = require("mongoose");
import Promise = require("bluebird");
mongoose.Promise = Promise;

Doing this is working fine. But I'd like to extend/override the type of the promise that is returned.

Here is an example of a function:

public getModel= () => {
    return MyModel.findOne().exec();
}

This function returns a _mongoose.Promise<MyModel> and I'd like to return a bluebird Promise<MyModel> because I know that is a bluebird promise.

Is there is anyway to change/extend/override the return type of mongoose query ? Should I write a custom definition file for my app ? Any others suggestions would be appreciated.

Thanks !

like image 386
Thomas Avatar asked Jul 19 '16 04:07

Thomas


3 Answers

Promise export as a variable in mongoose, so you can convert mongoose namespace as any first, and then set Promise to others.

  1. if you are using q lib.
    • install npm install --save q @types/q first. tsc version >= 2.0.
    • then add (<any>mongoose).Promise = Q.Promise;
  2. using bluebird lib, add code below.
    • import Bluebird = require("bluebird");
    • (<any>mongoose).Promise = Bluebird;
like image 175
ServerYang Avatar answered Nov 11 '22 17:11

ServerYang


Should I write a custom definition file for my app

Yes. It will mostly be a find and replace of Promise in the mongoose definition.

like image 1
basarat Avatar answered Nov 11 '22 16:11

basarat


The mongoose team updated the definition file and you can now plug in and use your own promise library by assigning the MongoosePromise<T>.

Create a main .d.ts file for your application and add this:

declare module "mongoose" {
    import Bluebird = require("bluebird");
    type MongoosePromise<T> = Bluebird<T>;
}

Reference this file in your project and now Mongoose returns Bluebird Promise !

This also works for others promises library.

EDIT latest typings version

declare module "mongoose" {
    import Bluebird = require("bluebird");
    type Promise<T> = Bluebird<T>;
}

See documentation here

like image 1
Thomas Avatar answered Nov 11 '22 18:11

Thomas