From 915726d778411adf42c36dde0a1532e2ccd1afbc Mon Sep 17 00:00:00 2001 From: "Neil A. Beardsley" Date: Fri, 8 Nov 2013 00:17:20 -0800 Subject: [PATCH] Adds support for custom primary ID names to the Document object. --- lib/document.js | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/lib/document.js b/lib/document.js index e83b9b2..654ef62 100644 --- a/lib/document.js +++ b/lib/document.js @@ -46,11 +46,11 @@ var buildSetter = function (key, def, model) { // has been created. if (value.isNew) { value.on('save', function (doc) { - self.attributes[def.field] = doc.id; + self.attributes[def.field] = doc[self.idKey]; self.pathStates.modify(def.field); }); } else { - this.attributes[def.field] = value.id; + this.attributes[def.field] = value[self.idKey]; this.pathStates.modify(def.field); } @@ -111,14 +111,15 @@ var Document = function Document (doc, table, constructor, db) { this.isNew = true; this.fields = {}; this.virtuals = {}; + this.idKey = this.constructor.schema.options.primaryKey; events.EventEmitter.call(this); var self = this; this.runPre('init', [this], function (err) { if (err) return handleError.call(self, err); - self.id = doc.id ? doc.id : null; - self.isNew = self.id ? false : true; + self[self.idKey] = doc[self.idKey] ? doc[self.idKey] : null; + self.isNew = self[self.idKey] ? false : true; self.attributes = {}; buildGetterAndSetters.call(self); self.hydrate(doc); @@ -193,7 +194,7 @@ Document.prototype.hydrate = function (doc) { var keys = Object.keys(data); keys.forEach(function (key) { self[key] = data[key]; - if(key !== 'id') self.pathStates.reset(key); + if(key !== self.idKey) self.pathStates.reset(key); }); }; @@ -311,7 +312,7 @@ Document.prototype.save = function (callback) { }); // Set the id of the document - data.id = self.id; + data[self.idKey] = self[self.idKey]; // Run the upsert query.upsert(data).exec(function (err, results) { @@ -323,7 +324,7 @@ Document.prototype.save = function (callback) { // If it's a new object then we need to set the id and change the // is new attribute to false if (self.isNew) { - self.id = results.insertId; + self[self.idKey] = results.insertId; self.isNew = false; } // Run the post middleware @@ -407,7 +408,7 @@ Document.prototype.toObject = function (options) { data = applyGetters(this, data, fields); } - data.id = this.id; + data[this.idKey] = this[this.idKey]; return data; };