1. Predefined schema modifiers
- Mongoose provides predefined schema modifiers to do some formatting with our added data
- lowercase
- uppercase
- trim
Usage:
var UserSchema = mongoose.Schema({
name: {
type: String,
trim: true
},
age: Number,
status: {
type: Number,
default: 1
}
})
Copy the code
2. Customize the Getters and Setters modifiers
In addition to mongoose’s built-in modifiers, we can also use the set modifier to format data as we add it. You can also use GET to format the data as it is retrieved by the instance.
var NewsSchema = mongoose.Schema({
title: "string",
author: String,
blogUrl: {
type: String,
set(url) {
if(! url)return url;
if (url.indexOf('http://') != 0 && url.indexOf('https://') != 0) {
url = 'http://' + url;
}
return url;
}
},
content: String,
status: {
type: Number,
default: 1
}
})
Copy the code