-
Notifications
You must be signed in to change notification settings - Fork 96
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding Context:'query' so validators get the updating document (#99)
- Loading branch information
1 parent
03854bc
commit e017e15
Showing
3 changed files
with
14 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,22 @@ | ||
import mongoose from 'mongoose'; | ||
const Schema = mongoose.Schema; | ||
|
||
const negativeAgeValidator = function () { | ||
// With option "context: 'query'", mongoose pass a Query object to validators when update or findAndModify a mongoose object | ||
// Plus findAndModify mongoose method put document in a $set object when update mongoose method don't | ||
// So you're forced to test these cases to retrieve your properties | ||
var age = (this.constructor.name === 'Query' ? (this.getUpdate().$set ? this.getUpdate().$set.age : this.getUpdate().age) : this.age); | ||
return (age > 0); | ||
}; | ||
|
||
const UserSchema = new Schema({ | ||
name: {type: String, required: true}, | ||
age: {type: Number}, | ||
age: {type: Number, validate: [negativeAgeValidator, 'Age couldn\'t be negative']}, | ||
created: {type: Boolean, 'default': false}, | ||
time: {type: Number}, | ||
pets: [{type: Schema.ObjectId, ref: 'Pet'}] | ||
}); | ||
|
||
const UserModel = mongoose.model('User', UserSchema); | ||
|
||
export default UserModel; | ||
export default UserModel; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters