Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created September 15, 2012 16:58
Show Gist options
  • Save davybrion/3728826 to your computer and use it in GitHub Desktop.
Save davybrion/3728826 to your computer and use it in GitHub Desktop.
code snippets for "Using Mongoose’s Setters To Get Calculated Properties" post
var invoiceSchema = new Schema({
companyId: { type: ObjectId, required: true },
customerId: { type: ObjectId, required: true },
invoiceNumber: { type: String, required: true, unique: true },
date: { type: Date, required: true },
dueDate: { type: Date, required: true },
paid: { type: Boolean, required: true, default: false },
activityId: { type: ObjectId, required: true },
totalHours: { type: Number, required: true },
hourlyRate: { type: Number, required: true },
totalExcludingVat: { type: Number, required: true },
vat: { type: Number, required: true },
totalIncludingVat: { type: Number, required: true }
});
invoiceSchema.path('totalExcludingVat').set(function(value) {
this.vat = value * 0.21;
this.totalIncludingVat = value * 1.21;
return value;
});
describe('given an invoice', function() {
var invoice = new Invoice();
describe('when you set its totalExcludingVat property', function() {
invoice.totalExcludingVat = 1000;
it('should automatically set the vat property', function() {
expect(invoice.vat).toEqual(210);
});
it('should automatically set the totalIncludingVat property', function() {
expect(invoice.totalIncludingVat).toEqual(1210);
});
});
});
describe('given an invoice created with a totalExcludingVat value', function() {
var invoice = new Invoice({ totalExcludingVat: 1000 });
it('should contain the correct vat value', function() {
expect(invoice.vat).toEqual(210);
});
it('should contain the correct totalIncludingVat property', function() {
expect(invoice.totalIncludingVat).toEqual(1210);
});
});
invoice.totalExcludingVat = 1000;
invoice['totalExcludingVat'] = 1000;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment