Home > OS >  How does a Mongoose Schema map to a collection in MongoDB?
How does a Mongoose Schema map to a collection in MongoDB?

Time:10-10

Apologies for the really basic question but I'm mildly perplexed. I'm using Mongoose in my Express Node server to post to Mongo and I've just realised the two Models/Schemas are not the exact same name as the collections in MongoDB they're posting to. Everything works, the API endpoints post to the correct collections but I can't work out how or why. What is the link between a Mongoose model/schema, and the MongoDB collection?

Obviously my MONGODB_URI environment variable points to my database, but there are no other references to collections and specifically which collection an API endpoint should post to, bar the Model, which is a different name to the collection.

For example, my Post model, below, does send data (through the api) to the posts collection, but I can't work out how it knows that's the correct collection and it's bugging me.

const PostSchema = new Schema({
...
});

const Post = mongoose.model('Post', PostSchema);
module.exports = Post;

As a test I totally renamed the variables above to something completely unrelated

const TrevorSchema = new Schema({
...
});

const Trevor = mongoose.model('Trevor', TrevorSchema);
module.exports = Trevor;

and a new collection was created with a pluralised name of model, 'Trevors' was created, so does Mongoose look for a pluralised name of the model to map to? Cheers, Matt

CodePudding user response:

Taking reference from some of the link from Mongoose docs itself

  1. Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. Link to docs

  2. The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database. Link to docs

From the docs, it is clear that they would auto handle conversion of a singluar model name to plural.

We can take a look at their codebase, where when you call the mongoose.model, internally this function gets called, which in return pluralize your model name and create a collection in Mongodb.

It looks like starting 5.0 Mongoose, also provides us a way to disable pluralization

  • Related