【问题标题】:typescript model adding mongoose authentication打字稿模型添加猫鼬身份验证
【发布时间】:2018-10-24 00:40:19
【问题描述】:

我的问题是当我尝试将猫鼬护照添加到我的架构时,我收到了错误消息:

export interface IUserModel extends IUser, Document { };

export let userSchema = new Schema({
    username: { type: String, required: true, unique: true }
}

firstName: { type: String, required: true },
const passportLocalMongoose = require("passport-local-mongoose");
userSchema.plugin(passportLocalMongoose);
export let User: Model<IUserModel> = model<IUserModel>("User", userSchema);

我添加到 app.ts(主文件):

import { User } from "./schemas/user";
let passport = require("passport");
passport.use(new localstrategy(User.authenticate()));

然后我收到错误消息:

错误 TS2339:属性 authenticate 不存在于类型 Model&lt;IUserModel&gt;

如果你知道答案,请帮助我。

【问题讨论】:

  • 您能指出我们说明 mongoose 模型具有 .authenticate() 方法的文档吗?
  • 据我所知 require("passport-local-mongoose") 会提供这个插件。
  • @libik 你怎么看这个:我将用 jwt 替换 mongoose 身份验证?
  • 啊,谢谢,也许我知道答案了

标签: typescript authentication mongoose restful-authentication


【解决方案1】:

Typescript 基本上不知道某些东西注入了一些额外的值。

我一直在用 express 解决类似的问题。要表达req: express.Request,我需要注入state,这样我就可以通过我的中间件使用我自定义的req.state

这是破解:

import { State } from './index';

declare module 'express' {
    interface Request {
        state: State;
    }
}

(State 只是 Typescript 模型):

export type State = {
    correlationId?: string;
    sessionId?: string;
    logger: Logger;
    out: any;
};

我认为你可以做类似的事情(让我们试试,如果不工作,修复它,如果你让它工作,请编写正确的解决方案,以便其他人可以使用它)

declare module 'mongoose' {
    interface Model {
        authenticate: Function;
    }
}

还有一个“hacky”解决方案 - 只需将其保存到 :any 变量然后使用它,打字稿不会用它控制任何东西(另一方面,这也不完美,因为你失去了使用打字稿的一些优势- 但如果只是应用程序的一小部分,你可以这样做)

import { User } from "./schemas/user";
let passport = require("passport");
const userThatCanDoAnything: any = User;
passport.use(new localstrategy(userThatCanDoAnything.authenticate()));

【讨论】:

    猜你喜欢
    • 2017-01-20
    • 2012-01-07
    • 2014-02-15
    • 2018-10-09
    • 2012-08-12
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2020-05-11
    相关资源
    最近更新 更多