Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
});
};

Expand Down Expand Up @@ -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) {
Expand All @@ -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
Expand Down Expand Up @@ -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;
};

Expand Down