Moongoose Model.find() returns empty array when i have uppercase letter in the table name

Viewed 42

When the table name includes a capital letter (e.g. fooBar), Moongoose Model.find() returns an empty array. If I change both the table name and the search string to be lowercase without changing anything else - it works fine.

Is this expected?

1 Answers

I think I have read somewhere about collection names being treated by default as lowercase inside of mongoose. I always circumvent it by using models:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const FoobarSchema = new Schema({
    name: { type: String }
}, { collection: 'fooBar' });

module.exports = mongoose.model('fooBar', FoobarSchema);

The important part is what you name the collection in the Schema definition. In the export that 'fooBar' can be named whatever you want and is a means to reference the model in your code.

Related