简体   繁体   English

NodeJS + TypeScript,猫鼬自定义界面无法扩展猫鼬。

[英]NodeJS+TypeScript, mongoose custom interface doesn't extend mongoose.Document properly

I'm relatively new to typescript, so I partially followed this guide: http://brianflove.com/2016/11/11/typescript-2-express-mongoose-mocha-chai/ 我是打字机的新手,所以我部分遵循了该指南: http : //brianflove.com/2016/11/11/typescript-2-express-mongoose-mocha-chai/

And I ended up with the following code(only the relevant parts): 最后,我得到了以下代码(仅相关部分):

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

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

and: 和:

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();

And according to the editor, it should work, however newUser only has the properties I gave it after compiling. 并且根据编辑器,它应该可以工作,但是newUser仅具有我在编译后提供的属性。

My setup is pretty much identical with the one in the tutorial. 我的设置与本教程中的设置几乎相同。

Could anyone tell me what am I doing wrong? 谁能告诉我我在做什么错?

Apparently, my entire approach was wrong. 显然,我的整个方法是错误的。

Creating a newUser with <IUserModel>{...} will simply create an object that matches its interface parameters, and nothing else, so in this case an object filled with username, password, etc., and not an actual model instance. 使用<IUserModel>{...}创建newUser只会创建一个与其接口参数匹配的对象,而不会其他任何东西,因此在这种情况下,将使用用户名,密码等填充对象,而不是实际的模型实例。

Also it doesn't even relate to the connection above it, which is something I completely missed. 而且它甚至与上面的连接都不相关,这是我完全想念的。

So instead I just had to do the following: 因此,我只需要执行以下操作:

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

This creates the proper model instance I wanted. 这将创建我想要的适当的模型实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM