使用TypeScript创建Mongoose模型 - 子文档

7

我正在按照这篇文章的指南,使用typescript实现mongoose模型:https://github.com/Appsilon/styleguide/wiki/mongoose-typescript-models。但是当处理子文档数组时,我不确定该如何操作。假设我有以下模型和模式定义:

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 { }

以下是将新宠物添加到用户的 pet 子文档的代码:

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异常:

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

在使用上面链接中概述的mongoose模型处理子文档时,这是正确的方法吗?

我以前没有用 TypeScript 创建过 Mongoose 模型。我猜 let pet: IPetModel = userModel.pets.create(newPet); 是不正确的。你能试试这个解决方案吗?addNewPet = (userId: string, newPet: IPet) => { var _user = mongoose.model("User", userSchema); let userModel: IUserModel = await this._user.findById(userId); userModel.pets.push(newPet); await userModel.save(); }希望对你有所帮助。 - dnp1204
你能否尝试在上面使用类而不是接口?这只是一个直觉,但我知道在Angular应用程序中,Typescript元数据(类型等)不会出现在编译代码中,包括接口!这意味着mongoose正在请求该嵌套模型/模式的构造函数,但它找不到它,因为接口在编译中消失了。 - Zlatko
1个回答

0
你可以尝试使用这个包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' } }); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接