Model of the Mongodb

Asked

Viewed 219 times

2

Hello! I’m starting to use Mongodb with Mongoose on Nodejs and I’m finding a strange behavior when creating Models mesus on Mongodb. Example:

mongoose.connect('mongodb://localhost/db_teste');

const PersonSchema = new Schema({
    name: {
        first: String,
        last: String
    }
});

const Person = mongoose.model('Person', PersonSchema);

This code should create the Model "Person", but when I run a "show Collections" in Mongo, via prompt, in my DB "db_teste" appears "People" instead of "Person". I also created a "test" model and appeared "tests" (with an extra "s"").

What is going on?

1 answer

2


It is a standard behavior of Mongoose that defines the name of collection as the plural of the name of model, therefore person turned people and teste turned testes.

You can override this behavior by manually setting the value of collection:

const PersonSchema = new Schema({
    name: {
        first: String,
        last: String
    }
}, { collection: 'person' });

Note in the last line, where the name of the collection.

  • Okay, it worked perfectly. I wonder if it is also possible to disable this behavior. Thank you

  • I don’t think so, I’d have to look for better documentation. I personally have never used Mongoose (nor did I even know this question), so I can’t answer you for sure if it’s possible.

  • I read the documentation and I think there is no way to disable, because in the Mongoose standard the model has a format defined as Mongoose#model(name, [schema], [collection], [skipInit]) and can also be set the name as schema.set('collection', 'actor');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.