1

Here is my code:

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/miniRDS", {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
}, (err) => {
    if(!err){
        console.log("Connected")
    }else{
        console.log("Couldn't connect!");
    }
});

const tests = new mongoose.Schema({
    subject: {
        type: String,
        required: true,
        default: "ict"
    },
    date: {
        type: String,
        required: true,
        default: "01-01-2021"
    }
});

const testsModel = mongoose.model("classTests", tests);
const s = new testsModel({
    subject: "english",
    date: "12-01-2021"
});

s.save();

I am using mongoose version 5.11.11. And I am facing difficulty when I try to create a collection with camelCase name using mongoose model.

In the above codes, It should create a collection name "classTests", instead it creates "classtests". how can I achieve "classTests"? Thanks

Shofiul
  • 50
  • 1
  • 8

3 Answers3

5

you can use it as:

module.exports = mongoose.model("user_notification_preference", NotificationPreference, "userNotificationPreferences");

three parameters:(the name you want to use as camel, schema, the actual name)

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
2

Solution :

To Resolve this, We can use a Plural name in the collection field

const mongoose = require('mongoose');
const AssessmentAttemptSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Types.ObjectId,
        required: true,
    },
    verificationToken: {
        type: String,
        required: true,
        unique: true,
    },
}, {
    timestamps: true,
    collection: 'assessmentAttempts',
});

module.exports = mongoose.model('AssessmentAttempt', AssessmentAttemptSchema);

So for this case, we are using assessmentAttempts to save the collection name as CamelCase.

End Result: Mongo DB : Sample Collection

MongoDB Collection Name Restrictions Docs : Reference Link

Mr.Singh
  • 1,421
  • 6
  • 21
  • 46
1

Mongoose automatically looks for the plural, lowercased version of your model name, please check this documentation, so you can't create a collection with camelCase in mongoose

Mohammad Yaser Ahmadi
  • 4,664
  • 3
  • 17
  • 39