【问题标题】:Mongoose: schema methods that reference other schema methods?Mongoose:引用其他模式方法的模式方法?
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 哦,我没有意识到在填充对象上调用架构方法会引用填充后的对象......天哪。好的,谢谢!
    猜你喜欢
    • 2014-05-09
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多