-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproduct.js
60 lines (53 loc) · 1.43 KB
/
product.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
var mongoose = require('mongoose');
var Category = require('./category');
module.exports = function(db, fx){
var productSchema = {
name: { type: String, required: true },
// Pictures must start with "http://"
pictures: [{ type: String, match: /^http:\/\//i }],
price: {
amount: {
type: Number,
required: true,
set: function(v) {
this.internal.approximatePriceUSD =
v / (fx()[this.price.currency] || 1);
return v;
}
},
// Only 3 supported currencies for now
currency: {
type: String,
enum: ['USD', 'EUR', 'GBP'],
required: true,
set: function(v) {
this.internal.approximatePriceUSD =
this.price.amount / (fx()[v] || 1);
return v;
}
}
},
category: Category.categorySchema,
internal: {
approximatePriceUSD: Number
}
};
var schema = new mongoose.Schema(productSchema);
schema.index({ name: 'text' });
var currencySymbols = {
'USD': '$',
'EUR': '€',
'GBP': '£'
};
/*
* Human-readable string form of price - "$25" rather
* than "25 USD"
*/
schema.virtual('displayPrice').get(function() {
return currencySymbols[this.price.currency] +
'' + this.price.amount;
});
schema.set('toObject', { virtuals: true });
schema.set('toJSON', { virtuals: true });
return db.model('Product', schema, 'products');
};