Why does mongoose always add an s to the end of my collection name


Question

For example, this code results in a collection called "datas" being created

var Dataset = mongoose.model('data', dataSchema);

And this code results in a collection called "users" being created

var User = mongoose.model('user', dataSchema);

Thanks

1
102
5/11/2012 7:18:39 AM

Accepted Answer

Mongoose is trying to be smart. You can however force it to be whatever you want:

var dataSchema = new Schema({..}, { collection: 'data' })

167
5/11/2012 11:49:04 PM

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);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon