猫鼬承诺与蓝鸟和打字稿 [英] Mongoose Promise with bluebird and typescript

查看:91
本文介绍了猫鼬承诺与蓝鸟和打字稿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用nodejs/typescript和mongodb数据库开发一个应用程序. 要查询数据库,我正在使用猫鼬.

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.

以下是一个函数示例:

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

此函数返回一个_mongoose.Promise<MyModel>,我想返回一个蓝鸟Promise<MyModel>,因为我知道那是一个蓝鸟的诺言.

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.

谢谢!

推荐答案

猫鼬团队更新了定义文件,现在您可以通过分配MongoosePromise<T>来插入和使用自己的Promise库.

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

为您的应用程序创建一个主要的.d.ts文件,并添加以下内容:

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

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

在您的项目中引用此文件,现在Mongoose返回Bluebird Promise!

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

这也适用于其他承诺库.

This also works for others promises library.

EDIT 最新输入版本

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

请参见文档此处

这篇关于猫鼬承诺与蓝鸟和打字稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆