23

It all works fine until I want to create a collection named 'Mice' for example. Both Mouses and Mices are unacceptable. Would be good if there is an option to set this in the config. Comments: thanks for the suggestion, I am using Mongoose.

swogger
  • 1,079
  • 14
  • 30
  • What do you mean? Where does MongoDB do this? I have never known this functionality – Sammaye Mar 13 '14 at 21:51
  • 1
    Perhaps you could specify the ODM you are using, since it is that which is adding the plural names. And there usually will be a way to fix that. – Neil Lunn Mar 13 '14 at 22:06
  • 2
    possible duplicate of [Mongoose -- Force collection name](http://stackoverflow.com/questions/7486528/mongoose-force-collection-name) – WiredPrairie Mar 13 '14 at 22:34

3 Answers3

64

If you name your model 'mouse', Mongoose will actually pluralize the collection name correctly to 'mice' (see source code).

But you can also explicitly name your collection when creating a model by passing it as the third parameter to model:

var Mice = mongoose.model('Mice', MouseSchema, 'Mice');
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
3

API structure of mongoose.model is this: Mongoose#model(name, [schema], [collection], [skipInit])

What mongoose do is that, When no collection argument is passed, Mongoose produces a collection name by pluralizing the model name. If you don't like this behavior, either pass a collection name or set your schemas collection name option.

Example

var schema = new Schema({ name: String }, { collection: 'actor' });

// or

schema.set('collection', 'actor');

// or

var collectionName = 'actor' var M = mongoose.model('Actor', schema, collectionName);

For more information check this link: http://mongoosejs.com/docs/api.html#index_Mongoose-model

Nishank Singla
  • 909
  • 8
  • 15
0

Here is the code, How you can understand how mongoose produce pluralize forms

function pluralize(str) {
  var found;
  str = str.toLowerCase();
  if (!~uncountables.indexOf(str)) {
    found = rules.filter(function(rule) {
      return str.match(rule[0]);
    });
    if (found[0]) {
      return str.replace(found[0][0], found[0][1]);
    }
  }
  return str;
}

Reference Link: https://github.com/vkarpov15/mongoose-legacy-pluralize/blob/master/index.js

Maulik Sakhida
  • 471
  • 4
  • 15