Home > Back-end >  How to load mongoose Schema from the collection name
How to load mongoose Schema from the collection name

Time:11-08

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.

CodePudding user response:

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

const AuthorSchema = require('mongoose').model('Author').schema;

CodePudding user response:

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.

  • Related