簡體   English   中英

NodeJS + TypeScript,貓鼬自定義界面無法擴展貓鼬。

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

我是打字機的新手,所以我部分遵循了該指南: 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僅具有我在編譯后提供的屬性。

我的設置與本教程中的設置幾乎相同。

誰能告訴我我在做什么錯?

顯然,我的整個方法是錯誤的。

使用<IUserModel>{...}創建newUser只會創建一個與其接口參數匹配的對象,而不會其他任何東西,因此在這種情況下,將使用用戶名,密碼等填充對象,而不是實際的模型實例。

而且它甚至與上面的連接都不相關,這是我完全想念的。

因此,我只需要執行以下操作:

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

這將創建我想要的適當的模型實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM