使用打字稿创建猫鼬模型

编程入门 行业动态 更新时间:2024-10-18 10:14:38
本文介绍了使用打字稿创建猫鼬模型-子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I am in the process of implementing mongoose models with typescript as outlined in this article: github/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?

推荐答案

您可以尝试此软件包 www.npmjs/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' } });

更多推荐

使用打字稿创建猫鼬模型

本文发布于:2023-11-22 13:34:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617618.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!