code:
// Built in validators
const mongoose = require(‘mongoose’)
mongoose.connect(‘mongodb://localhost/playground’)
// .then(() => console.log(‘Connected to mongodb…’))
.catch(err => console.log(‘Coud not connect to mongodb’, err))
const CourseSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 255
},
category: {
type: String,
enum: [‘web’, ‘net’, ‘app’]
},
author: String,
// Custom Validator
tags: {
type: Array,
validate: {
isAsync: true,
validator: function(v, callback) {
// setTimeout(() => {
// const result = v && v.length > 0;
// callback(result)
// }, 2000)
return v && v.length > 0;
},
messasge: ‘A course should have atleast one tag.’
}
},
date: { type: Date, default: Date.now },
isPublished: Boolean,
price: {
type: Number,
required: function() { return this.isPublished}
}
})
const Course = mongoose.model(‘Course’, CourseSchema)
async function createCourse() {
const course = new Course({
name: ‘Angular course’,
category: ‘web’,
author: ‘Sid’,
tags: ,
isPublished: true,
price: 10
})
try {
// await course.validate()
const result = await course.save()
console.log(result);
}
catch (err) {
console.log(err.message);
}
}
createCourse();