Jorge Rivera
Jorge Rivera

Reputation: 775

Mongoose collection naming bug?

I found this (I think?) undesirable behavior in mongoose 3.8.12, when you create a new mongoose model by default it makes its name plural adding an 's' which is perfectly normal, when the model's name already ends with an 's' then save it as it is (expected behavior). The problem is when you have two different models with the same name but one plural and the other singular, then mongoose allows you two create the two but uses the same collection in mongo to store both.

let's say I have a collection named 'car':

mongoose.model('Car', schema);

and a collection 'cars':

mongoose.model('Cars', schema);

both are saved in mongo as 'cars'

I don't think that is the expected behavior.

Upvotes: 0

Views: 514

Answers (1)

Justin Case
Justin Case

Reputation: 1513

http://mongoosejs.com/docs/api.html#index_Mongoose-model

When no collection argument is passed, Mongoose produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option.

Since Car turns into Cars, and Cars is already plural you end up with the same collection name. Models are generally given the singular name. The link above lists several methods to set a custom collection name.

Of course, you can always create a new issue on the project's GitHub repo.

Upvotes: 1

Related Questions