我创建了一个Mongoose Schema并为Model添加了一些名为Campaign的静态方法.
如果我是console.log Campaign我可以看到它上面的方法.问题是我不知道在哪里添加这些方法,以便Typescript也知道它们.
如果我将它们添加到我的CampaignModelInterface,它们仅适用于模型的实例(或者至少TS认为它们是).
campaignSchema.ts
export interface CampaignModelInterface extends CampaignInterface, Document {
// will only show on model instance
}
export const CampaignSchema = new Schema({
title: { type: String, required: true },
titleId: { type: String, required: true }
...etc
)}
CampaignSchema.statics.getLiveCampaigns = Promise.method(function (){
const now: Date = new Date()
return this.find({
$and: [{startDate: {$lte: now} }, {endDate: {$gte: now} }]
}).exec()
})
const Campaign = mongoose.model<CampaignModelInterface>('Campaign', CampaignSchema)
export default Campaign
Run Code Online (Sandbox Code Playgroud)
我也试过通过Campaign.schema.statics访问它,但没有运气.
任何人都可以建议如何让TS了解模型中存在的方法,而不是模型实例?
我正在使用本文中概述的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 { }
Run Code Online (Sandbox Code Playgroud)
将新宠物添加到user.pet子文档的代码:
addNewPet = (userId: string, newPet: IPet){
var _user = mongoose.model<IUserModel>("User", userSchema);
let …Run Code Online (Sandbox Code Playgroud)