【问题标题】:NodeJS+TypeScript, mongoose custom interface doesn't extend mongoose.Document properlyNodeJS+TypeScript,mongoose 自定义界面没有正确扩展 mongoose.Document
【发布时间】:2018-03-26 13:32:40
【问题描述】:

我对打字稿比较陌生,所以我部分遵循了本指南: http://brianflove.com/2016/11/11/typescript-2-express-mongoose-mocha-chai/

我最终得到了以下代码(仅相关部分):

import { Document } from "mongoose";
import { IUser } from "../interfaces/user";

export interface IUserModel extends IUser, Document {
  // custom methods for your model would be defined here
}

和:

import { IUserModel } from "./models/user";    

let connection: mongoose.Connection = mongoose.createConnection(MONGODB_CONNECTION);
this.model.user = connection.model<IUserModel>('User', userSchema);

var newUser: IUserModel = <IUserModel>{username:'asd',password:'bsd',email:'lol',admin:false};

newUser.save();

根据编辑的说法,它应该可以工作,但是 newUser 只有我在编译后给它的属性。

我的设置与教程中的设置几乎相同。

谁能告诉我我做错了什么?

【问题讨论】:

    标签: node.js mongodb typescript mongoose


    【解决方案1】:

    显然,我的整个方法都是错误的。

    使用&lt;IUserModel&gt;{...} 创建一个 newUser 只会创建一个与其接口参数匹配的对象,而不是其他任何东西,因此在这种情况下,一个对象填充了用户名、密码等,而不是实际的模型实例。

    而且它甚至与上面的连接无关,这是我完全错过的。

    所以我只需要执行以下操作:

    var newUser = new this.model.user({ username: 'asd', password: 'bsd', email: 'lol', admin: false });
    newUser.save();
    

    这会创建我想要的正确模型实例。

    【讨论】:

      猜你喜欢
      • 2019-11-13
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 2020-09-16
      • 2016-11-19
      • 1970-01-01
      相关资源
      最近更新 更多