Skip to content

Commit

Permalink
Adding Context:'query' so validators get the updating document (#99)
Browse files Browse the repository at this point in the history
  • Loading branch information
quick691fr authored and ekryski committed Jul 7, 2016
1 parent 03854bc commit e017e15
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
4 changes: 3 additions & 1 deletion src/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ class Service {
new: true,
overwrite: this.overwrite,
runValidators: true,
context: 'query',
setDefaultsOnInsert: true
}, params.mongoose);

Expand All @@ -167,7 +168,8 @@ class Service {
// If we are updating multiple records
let options = Object.assign({
multi: id === null,
runValidators: true
runValidators: true,
context: 'query'
}, params.mongoose);

if (id !== null) {
Expand Down
12 changes: 10 additions & 2 deletions test/models/user.js
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;
2 changes: 1 addition & 1 deletion test/test-app.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,4 @@ if (!module.parent) {
console.log('Feathers Todo mongoose service running on 127.0.0.1:3030');
}

module.exports = app;
module.exports = app;

0 comments on commit e017e15

Please sign in to comment.