|
1
|
|
|
var mongoose = require('mongoose') |
|
2
|
|
|
var Schema = mongoose.Schema |
|
3
|
|
|
var addressSchema = require('./common/address') |
|
4
|
|
|
var phoneSchema = require('./common/phone') |
|
5
|
|
|
|
|
6
|
|
|
var customerSchema = new Schema({ |
|
7
|
|
|
name: { type: String, required: true }, |
|
8
|
|
|
address: [ addressSchema ], |
|
9
|
|
|
phone: [ phoneSchema ], |
|
10
|
|
|
createdOn: { type: Date, default: Date.now }, |
|
11
|
|
|
updatedOn: { type: Date, default: Date.now } |
|
12
|
|
|
}) |
|
13
|
|
|
|
|
14
|
|
|
customerSchema.pre('save', function (next) { |
|
15
|
|
|
// change the updatedOn field to current date |
|
16
|
|
|
this.updatedOn = new Date() |
|
17
|
|
|
next() |
|
18
|
|
|
}) |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Statics |
|
22
|
|
|
*/ |
|
23
|
|
|
|
|
24
|
|
|
customerSchema.statics = { |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Find customer by id |
|
28
|
|
|
* |
|
29
|
|
|
* @param {ObjectId} id |
|
30
|
|
|
* @api private |
|
31
|
|
|
|
|
32
|
|
|
load: function (_id) { |
|
33
|
|
|
return this.findOne({ _id }) |
|
34
|
|
|
.populate('name', 'address phone') |
|
35
|
|
|
.populate('customer.name') |
|
36
|
|
|
.exec(); |
|
37
|
|
|
},*/ |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* List customers |
|
41
|
|
|
* |
|
42
|
|
|
* @param {Object} options |
|
43
|
|
|
* @api private |
|
44
|
|
|
*/ |
|
45
|
|
|
|
|
46
|
|
|
list: function (options) { |
|
47
|
|
|
const criteria = options.criteria || {} |
|
48
|
|
|
const page = options.page || 0 |
|
49
|
|
|
const limit = options.limit || 30 |
|
50
|
|
|
return this.find(criteria) |
|
51
|
|
|
.populate('name', 'address phone') |
|
52
|
|
|
.sort({ createdAt: -1 }) |
|
53
|
|
|
.limit(limit) |
|
54
|
|
|
.skip(limit * page) |
|
55
|
|
|
.exec() |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
module.exports = mongoose.model('Customer', customerSchema) |
|
60
|
|
|
|