【问题标题】:Mongoose Schema with nested properties in typescript打字稿中具有嵌套属性的猫鼬模式
【发布时间】:2019-07-12 10:11:00
【问题描述】:

从打字稿开始,我尝试声明一个看起来像这样的 Mongoose 模式:

User
{
    name : { type: String, required: true },
    ...
    credentials :
    {
        email : { type : String, required : true },
        password : { type : String, required : true },
    },
    ...
}

我试过了:

import { Document, Types, Schema, Model, model } from "mongoose";

export interface ICredentials
{
    email?:string,
    password?:string,
}

export interface IUser extends Document
{
    name?:string;
    credentials?:ICredentials;
}

export var UserSchema:Schema = new Schema
({
    name            : { type : String, required : true },
    credentials     : 
    {
        email       : { type : String, required : true },
        password    : { type : String, required : true },
    },
});

export const User:Model<IUser> = model<IUser>("User", UserSchema);

当我想创建一个新用户时,它似乎工作正常。但它没有凭据。 我试过U.credentials.email = "test@yopmail.com",但它不起作用。 我怎么能做到? 我很确定我需要声明一个实现 ICredentials 的类,但我不熟悉打字稿。

【问题讨论】:

标签: typescript mongoose nested


【解决方案1】:

我最近遇到了类似的问题,我是这样解决的; 我只是添加了一个类型断言..

U.credentials!.email = "test@yopmail.com"

【讨论】:

猜你喜欢
  • 2016-04-01
  • 2019-03-22
  • 2014-02-15
  • 2016-01-05
  • 2017-01-20
  • 2021-01-05
  • 2015-09-21
  • 2016-08-28
  • 2017-06-30
相关资源
最近更新 更多