Mongoose:引用其他模式方法的模式方法?

时间:2018-03-23 19:29:06

标签: mongodb mongoose mongoose-schema

我正在尝试使用引用不同模型的架构方法的架构方法。例如:

模型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()中调用方法时,mongoose是否应该能够抓取这些子项并将它们自动转换为db对象?或者在toJSONFor我应该做的事情如下:

subthings: await Promise.all(this.subthings.map(subthing => 
      Subdomain.findById(subthing).then(foundThing => foundThing.myMethod())
    ))

那是不是很糟糕?在另一个模型中引用模型似乎非常奇怪

1 个答案:

答案 0 :(得分:1)

您是否尝试过使用Mongoose的填充方法?这似乎根据他们的文档为您提供文档。请参阅:http://mongoosejs.com/docs/populate.html