onlinecode

Enums in Mongoose – onlinecode

Enums in Mongoose

Enums in Mongoose – onlinecode

In this post, we will give you information about Enums in Mongoose – onlinecode. Here we will give you detail about Enums in Mongoose – onlinecode And how to use it also give you a demo for it if it is necessary

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

Typescript enums

You can also use Typescript Enums.
At runtime, TypeScript enums are just POJOs where the object’s values are the enum values.
When you set enum to an object, Mongoose will run Object.values() on the object to get the desired values.

enum Status {
  Valid,
  Invalid
};

const testSchema = new mongoose.Schema({
  rating: {
    type: Number,
    enum: Rating
  xw}
});

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

await Test.create({ name: 'invalid' }); // throws validation error
await Test.create({ name: 'Valid' }); // works

A mongoose is a small, carnivorous mammal that is found in Africa, Asia, and southern Europe. They are known for their ability to kill venomous snakes, and they have been used for centuries to control snake populations. Mongooses are also popular pets, but they can be difficult to care for and are not recommended for everyone.

Here are some of the pros and cons of owning a mongoose:

Pros:

Cons:

If you are considering getting a mongoose as a pet, it is important to do your research and make sure that you are prepared to provide the proper care. Mongooses are not for everyone, but they can make great companions for the right people.

Here are some additional facts about mongooses:

Hope this code and post will helped you for implement Enums in Mongoose – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Exit mobile version