JSilv
JSilv

Reputation: 1055

Mongoose: schema methods that reference other schema methods?

I am trying to work on a schema method that references the schema method for a different model. For example:

Model 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())
  }
}

Model 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
  }
}

Erroring to say: "subthing.myMethod is not a function"

My question is, should mongoose be able to grab these subthings and cast them automatically to their db objects when I call the method in DomainSchema.toJSONFor()? Or in toJSONFor should I be doing something like:

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

And is that bad? It seems really weird to reference a model within another model.

Upvotes: 0

Views: 358

Answers (1)

Aaron Rumery
Aaron Rumery

Reputation: 562

Have you tried using Mongoose's populate method? That seems to cast documents for you according to their documentation. Please see: http://mongoosejs.com/docs/populate.html

Upvotes: 1

Related Questions