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 !
Promise
export as a variable in mongoose, so you can convert mongoose
namespace as any first, and then set Promise
to others.
q
lib.
npm install --save q @types/q
first. tsc
version >= 2.0.(<any>mongoose).Promise = Q.Promise;
bluebird
lib, add code below.
import Bluebird = require("bluebird");
(<any>mongoose).Promise = Bluebird;
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With