Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate nested entities in mongoose?

Tags:

People also ask

How does populate work in mongoose?

Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

How do mongooses make relationships?

To model relationships between connected data, you can reference a document or embed it in another document as a sub document. Referencing a document does not create a “real” relationship between these two documents as does with a relational database. Referencing documents is also known as normalization.

What is virtual populate in mongoose?

Populate. Mongoose also supports populating virtuals. A populated virtual contains documents from another collection. To define a populated virtual, you need to specify: The ref option, which tells Mongoose which model to populate documents from.


I have the following mongoose schema structure

userSchema = new Schema({
    roles: [
        role: {type: Schema.Types.ObjectId, ref: 'Role' }
    ]
})

rolesSchema = new Schema({
  name: String,
  roleEntities: [
    {
      entity : {type: Schema.Types.ObjectId, ref: 'RoleEntity' },
      abilities : [{type: Schema.Types.ObjectId, ref: 'Ability' }]
    }
  ]
}

roleEntitiesSchema = new Schema({
  name: String
})

abilitiesSchema = new Schema({
  name: String
})

How can i populate all these nested documents while doing a find on the USER model?

I tried using populate as below

User.find(ctx.request.query).populate(
      {path: 'roles.role'
      ,populate: { path: 'roleEntities.entity'}
    }).
    exec()

but it's not resolving roleEntities.entity