skip to Main Content

Ideally, for populate to work during queries in mongoose, both the schemas of that which is been populated and the calling schema needs to be imported in same file under same repo.

Now, I have a scenario where a schema called AuthorSchema was created by another internal micro-service in another repo which is pointing to the same database as my own service and I wish to populate it during my queries.

Is there a way to automatically decode the AuthorSchema from the author collection name after I’ve connected to the database?

E.g

let posts = await Post.find({})
            .populate("author", 'first_name last_name _id').limit(10)

Where I have created postSchema in my own service but authorSchema was created by another micro-service in another repo called author-management-microservice and as such I have no access to that schema.

What I would want is something like:

let AuthorSchema = mongoose.connection.decodeSchemaFromCollectionName('author');

Such that I can modify my query to something like

let posts = await Post.find({})
                .populate({path:"author", model:AuthorSchema, select:'first_name last_name _id'}).limit(10)

The reason I want something like this is because I have been battling with MissingSchemaError: Schema hasn't been registered for model "Author". whenever I try to populate author and I don’t want to copy around duplicate schema files across different micro-services.

2

Answers


  1. To get the schema from a registered Mongoose model, you need to access the schema specifically:

    const AuthorSchema = require('mongoose').model('Author').schema;
    
    Login or Signup to reply.
  2. Is there a way to automatically decode the AuthorSchema from the author collection name after I’ve connected to the database?

    No – the schema is saved at the code level, not the database level. There is no way to know the schema just from connecting to the database.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search