hagopj13 / node-express-boilerplate

A boilerplate for building production-ready RESTful APIs using Node.js, Express, and Mongoose
MIT License
6.99k stars 2.05k forks source link

Types and statuses as enums #226

Closed alkhachatryan closed 6 months ago

alkhachatryan commented 2 years ago

Hello. I'm new to Nodejs and found this briliant repo to work with. It helps me to understand how nodejs works, what expressjs is and so on. This is not a bug report, but a question related with nodejs, mongoDB and this boilerplate implementation.

I came to NodeJS from PHP and relational DBs stack and I got confused: don't you use enums in backend and integers in mongo? Let's say we have here column which can be enumed and replaced with numeric column type to make DB faster: user.role. As much as I read I see nobody uses integers and such type of columns, but strings: status, role and so on.

In PHP and relational DB stack we had enums and numeric values and in DB we stored the value of that enum so DB could query with that columns faster. Does not it work here?

ghost commented 2 years ago

Hi @alkhachatryan

Here is How Enums Work in Mongoose

Mongoose String and Number types have an enum validator. The enum validator is an array that will check if the value given is an item in the array. If the value is not in the array, Mongoose will throw a ValidationError when you try to save().


const testSchema = new mongoose.Schema({
  status: {
    type: String,
    enum: ['valid', 'invalid']
  }
})

const Test = mongoose.model('Test', testSchema);

await Test.create({ name: 'not a status' }); // throws validation error
await Test.create({ name: 'valid' }); // works