From 77e45cf3d52053c5f01ac2d438558654eb257819 Mon Sep 17 00:00:00 2001 From: Sebastien Blanchard Date: Thu, 7 Jul 2016 14:42:18 -0700 Subject: [PATCH] Adding Context:'query' so validators get the updating document --- src/service.js | 4 +++- test/models/user.js | 12 ++++++++++-- test/test-app.js | 2 +- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/service.js b/src/service.js index 27032a7c..97254024 100644 --- a/src/service.js +++ b/src/service.js @@ -141,6 +141,7 @@ class Service { new: true, overwrite: this.overwrite, runValidators: true, + context: 'query', setDefaultsOnInsert: true }, params.mongoose); @@ -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) { diff --git a/test/models/user.js b/test/models/user.js index 40e601a6..33c1c0d5 100644 --- a/test/models/user.js +++ b/test/models/user.js @@ -1,9 +1,17 @@ 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'}] @@ -11,4 +19,4 @@ const UserSchema = new Schema({ const UserModel = mongoose.model('User', UserSchema); -export default UserModel; \ No newline at end of file +export default UserModel; diff --git a/test/test-app.js b/test/test-app.js index 0f690113..15e5ebcd 100644 --- a/test/test-app.js +++ b/test/test-app.js @@ -47,4 +47,4 @@ if (!module.parent) { console.log('Feathers Todo mongoose service running on 127.0.0.1:3030'); } -module.exports = app; \ No newline at end of file +module.exports = app;