const mongoose = require('mongoose');
//var validate = require('mongoose-validator');
const postschema = mongoose.Schema({
userName :{
type : String,
required : true
},
status : {
type : Array ,
items : {
type : String ,
max: 20 ,
required : true
},
},
likes : {
type : Array ,
default : []
}
},
{ timestamps :{ createdAt: 'created_at',updatedAt: 'updated_at' }}
);
postschema.path('status').validate(function(v){
return v.length <=20;
},"The maximum length is 20 ");
module.exports = mongoose.model('Post' , postschema);
My validation function is not working. How can I validate my status Array of String. I want to validate each string of 20 characters
You can try like this:
const postschema = new Schema({
userName :{
type : String,
required : true
},
status: {
type: [{
type: Schema.Types.ObjectId,
ref: 'peopleModel'
}],
validate: [arrayLimit, '{PATH} exceeds the limit of 10']
}
});
function arrayLimit(val) {
return val.length <= 10;
}
i think it's that easy for status use;
status: [
{
type : String ,
maxLength: 20 ,
},
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.