1

Hello Stackoverflowers!

I got a strange issue with Mongoose creating a collection named "Safes".

here is my example code:

const mongoose = require('mongoose')
mongoose.connect('mongodb://mongodb:27017/test', { useNewUrlParser: true })

const Safe = mongoose.model('Safe', { name: String })

const safe = new Safe({ name: 'foobar' })
safe.save().then(() => console.log('done'))

when I open the database shell and issue this command:

mongo test --eval "db.getCollectionNames()"

its responds with:

MongoDB shell version v4.0.6
connecting to: mongodb://127.0.0.1:27017/test?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("f9cfa8b9-58e2-40b8-9907-ecd18039935a") }
MongoDB server version: 4.0.6
[ "saves" ]

Now, I tried to create a model with a collection names "Safes" and mongoose seems to change it from safes > saves ...

Has mongoose some kind of protected models that cannot be used?

2 Answers2

3

Seems like they set a rule on words ending with "fe" because they normally convert to plural as "ves" (knife -> knives).

You can set your own collection name by adding another argument to Schema:

const safeSchema = new Schema({ name: String }, { collection: 'safes' })
1

Mongooses util.toCollectionName generates a name of the collection based on the Schema name. It does use some regexes, one of them being:

  [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'],

Which maches safe and replaces it with saves.

source

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151