【发布时间】:2018-08-20 01:08:30
【问题描述】:
我正在使用 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 { }
将新宠物添加到 user.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.
使用上面链接文章中概述的猫鼬模型时处理子文档的方法是否正确?
【问题讨论】:
-
我之前没有用打字稿创建猫鼬模型。我猜让宠物:IPetModel = userModel.pets.create(newPet);是不正确的。你可以试试这个解决方案吗? addNewPet = (userId: string, newPet: IPet){ var _user = mongoose.model
("User", userSchema);让 userModel: IUserModel = await this._user.findById(userId); userModel.pets.push(newPet);等待 userModel.save(); } 希望对您有所帮助 -
你可以尝试使用类而不是接口吗?这只是一种预感,但我知道,即在 Angular 应用程序中,Typescript 元数据(类型等)无法编译为代码,其中包括接口! 意思是,猫鼬要求该嵌套模型的构造函数/schema,但找不到它,因为接口在编译中消失了。
标签: node.js mongodb typescript mongoose mongoose-models