Reputation: 29522
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 !
Upvotes: 6
Views: 5560
Reputation: 10167
As of this writing, there is an open issue in the typings file that is installed if you use typings install mongoose
to install the typings. Specificaly typings file that is loaded imports mpromise, and that import statement results in inclusion of the full mpromise module definition file by typings and included in your typings\modules\mongoose\index.d.ts
file.
Until this issue get's resolved, my workaround is to delete the module definition for ~mongoose~mpromise
and replace the following line in the index.d.ts
file:
import * as Promise from '~mongoose~mpromise';
with this one:
import Promise = require( "bluebird");
This is admittedly a temporary stop-gap as another call to typings install mongoose
would revert this fix. For the curious, my current set up includes: typings ( version 2.0.0 ), npm ( 3.10.9 ), and node ( v6.9.2 )
Upvotes: 0
Reputation: 29522
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
Upvotes: 1
Reputation: 79
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;
Upvotes: 5
Reputation: 275867
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.
Upvotes: 1