本文介绍了使用打字稿创建猫鼬模型-子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用本文概述的打字稿实现猫鼬模型: https://github.com/Appsilon/styleguide/wiki/mongoose-typescript-models ,并且不确定在处理子文档数组时如何转换.假设我有以下模型和架构定义:

I am in the process of implementing mongoose models with typescript as outlined in this article: https://github.com/Appsilon/styleguide/wiki/mongoose-typescript-models and am not sure of how this translates when you are working with arrays of subdocuments. Let's say I have the following model and schema definitions:

interface IPet {
    name: {type: mongoose.Types.String, required: true},
    type: {type: mongoose.Types.String, required: true}
}

export = IPet


interface IUser {
    email: string;
    password: string;
    displayName: string;
    pets: mongoose.Types.DocumentArray<IPetModel>
};

export = IUser;


import mongoose = require("mongoose");
import IUser = require("../../shared/Users/IUser");
interface IUserModel extends IUser, mongoose.Document { }

import mongoose = require("mongoose");
import IPet = require("../../shared/Pets/IPet");
interface IPetModel extends IPet, Subdocument { }

将新宠物添加到user.pet子文档的代码:

code that would add a new pet to the user.pet subdocument:

addNewPet = (userId: string, newPet: IPet){
    var _user = mongoose.model<IUserModel>("User", userSchema);
    let userModel: IUserModel = await this._user.findById(userId);
    let pet: IPetModel = userModel.pets.create(newPet);
    let savedUser: IUser = await pet.save();
}

在查看链接之后,这似乎是处理子文档所必需的理想方法.但是,这种情况似乎导致抛出CasterConstructor异常:

After reviewing the link, this seems to be the ideal approach necessary for handling subdocuments. However, this scenario seems to result in a CasterConstructor exception being thrown:

TypeError: Cannot read property 'casterConstructor' of undefined at Array.create.

使用上面链接文章中概述的猫鼬模型时,处理子文档是否正确?

Is it the right approach to dealing with Subdocuments when using mongoose models as outlined in the linked article above?

推荐答案

您可以尝试此软件包 https://www.npmjs.com/package/mongoose-ts-ua

@setSchema()
class User1 extends User {
    @prop()
    name?: string;

    @setMethod
    method1() {
        console.log('method1, user1');
    }
}

@setSchema()
class User2 extends User {
    @prop({ required: true })
    name?: string;

    @prop()
    child: User1;
}

export const User2Model = getModelForClass<User2, typeof User2>(User2);

用法

let u2 = new User2Model({ child: { name: 'u1' } });

这篇关于使用打字稿创建猫鼬模型-子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:23