Search code examples
mongodbmongoose

I want to get a model with a hyphen included name


Models with normal names can obtain results.

However, models with names containing hyphens cannot obtain results.

users-permissions,user contains data.

const db = await mongoose.connect("mongodb://URL", {...});


const userModel= db.model("user", new mongoose.Schema({}));
const usersPermissionsModel = db.model("users-permissions", new mongoose.Schema({}));


console.log(await userModel.find().limit(1)) // Object data
console.log(await usersPermissionsModel.find().limit(1)) // [], null array

I think the model name has a hyphen in it, so it doesn't query. Is that right?

Is there a solution?


Solution

  • TL;DR

    There's no problem with - in a mongo collection, nor do the mongoose naming conventions modify your users-permissions collection name. Check your DB if you have the right collection name, and that there are documents in the collection.


    When you create a schema & model in mongoose, then mongoose will automatically apply it's own naming convention when creating the the collection in the database.

    This is normally fine, but it looks like you already have some data in mongodb which you are trying to access with mongoose. You can override the collection name like so:

    const usersPermissionsSchema = new mongoose.Schema({}, { collection: 'users-permissions' })
    const usersPermissionsModel = db.model("users-permissions", usersPermissionsSchema);
    

    From the schema documentation:

    option: collection

    Mongoose by default produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. Set this option if you need a different name for your collection.

    Annoyingly that utils.toCollectionName isn't documented, but looking at the source code

    That led me to another repo containing the pluralize method, along with an SO question regarding the naming convention.

    But the rules in that pluralize method don't affect your "users-permissions" name, so I think you may actually have a typo or no models exist in that collection. Check out your database via CLI or a GUI tool like NoSQLBooster.