在打字稿中具有嵌套属性的 Mongoose 架构

Mongoose Schema with nested properties in typescript

提问人:T00rk 提问时间:2/19/2019 最后编辑:T00rk 更新时间:1/7/2021 访问量:2906

问:

从打字稿开始,我尝试声明一个 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);

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

TypeScript 猫鼬 嵌套

评论

0赞 aoi umi 3/16/2019
stackoverflow.com/questions/49228020/......

答:

0赞 Tron 1/7/2021 #1

我最近遇到了类似的问题,以下是我解决它的方法; 我只是添加了一个类型断言。

U.credentials!.email = "[email protected]"

评论

0赞 T00rk 1/19/2021
我使用 Typegoose npmjs.com/package/typegoose 解决了它。它工作正常