【发布时间】:2018-09-02 13:40:23
【问题描述】:
我正在尝试使用引用不同模型的模式方法的模式方法。例如:
模型 1:
const DomainSchema = new mongoose.Schema({
thing: { type: string, required: true },
subthings: [
{ type: mongoose.Schema.Types.ObjectId, ref: 'Subdomain' }
]
})
DomainSchema.methods.toJSONFor = function() {
return {
_id: this._id,
thing: this.thing,
subthings: this.subthings.map(subthing => subthing.mymethod())
}
}
模型 2:
const SubdomainSchema = new mongoose.Schema({ /* doesnt matter whats in here */ })
SubdomainSchema.methods.mymethod = function() {
return {
_id: this.id,
type: this.type,
name: this.name
}
}
说错了:"subthing.myMethod is not a function"
我的问题是,当我调用DomainSchema.toJSONFor() 中的方法时,猫鼬是否能够抓住这些子事物并将它们自动转换为它们的数据库对象?或者在toJSONFor 我应该做类似的事情:
subthings: await Promise.all(this.subthings.map(subthing =>
Subdomain.findById(subthing).then(foundThing => foundThing.myMethod())
))
那很糟糕吗?在另一个模型中引用一个模型似乎真的很奇怪。
【问题讨论】:
标签: mongodb mongoose mongoose-schema