javascriptnode.jsmongooseodm

Mongoose ODM saves wrong model name in MongoDB collection


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?


Solution

  • 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' })