From d002777da3082213f142a200e372239d21b65a69 Mon Sep 17 00:00:00 2001 From: Sergio Date: Fri, 19 May 2017 21:37:01 +1000 Subject: [PATCH] Adding an extra argument to virtual functions so that they can have access to the full object --- lib/schema.js | 2 +- test/model.js | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/lib/schema.js b/lib/schema.js index 252f8d71..3365202f 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -53,7 +53,7 @@ function generateVirtual(doc, defaultField, originalDoc, virtual) { } } else if ((typeof value === "function") && !Array.isArray(value._query)) { - field[path[path.length-1]] = value.call(doc); + field[path[path.length-1]] = value.call(doc, originalDoc); } else { if (util.isPlainObject(value)) { diff --git a/test/model.js b/test/model.js index bd9ad493..a56da771 100644 --- a/test/model.js +++ b/test/model.js @@ -705,6 +705,25 @@ describe('virtual', function(){ }) assert.equal(doc.numVirtual, 3); }); + it('Generate fields -- virtuals with access to parent', function() { + var Model = thinky.createModel(modelNames[0], { + id: String, + num: Number, + numbers: { + numVirtual: { + _type: 'virtual', + default: function(parentDoc) { + return parentDoc.num+2 + } + } + } + + }); + var doc = new Model({ + num: 1, numbers:{} + }) + assert.equal(doc.numbers.numVirtual, 3); + }); it('Generate fields -- manually', function() { var Model = thinky.createModel(modelNames[0], { id: String,