-
Notifications
You must be signed in to change notification settings - Fork 1
/
Product.js
executable file
·85 lines (82 loc) · 1.65 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProductScema = new Schema({
name: {
type: String,
required: true
},
category: {
type: String,
required: true
},
brand: {
type: String,
required: true
},
model: {
type: String
},
specification: String,
price: {
type: Number,
required: true
},
quantity: {
type: Number,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
});
/**
* Statics
*/
ProductScema.statics = {
/**
* Get product
* @param {ObjectId} id - The objectId of product.
* @returns {Promise<Product, APIError>}
*/
get (id) {
return this.findById(id)
.exec()
.then(product => {
if (product) {
return product;
}
const err = new APIError('No such product exists!', httpStatus.NOT_FOUND);
return Promise.reject(err);
});
},
/**
* List products in descending order of 'createdAt' timestamp.
* @param {number} skip - Number of products to be skipped.
* @param {number} limit - Limit number of products to be returned.
* @returns {Promise<User[]>}
*/
list ({
category = '',
brand = '',
sort = 'quantity',
sorder = 'desc',
skip = 0,
limit = 50
} = {}) {
let condition = {};
if (brand) {
condition.brand = brand;
}
if (category) {
condition.category = category;
}
const soringOrder = sorder === 'desc' ? -1 : 1;
return this.find(condition)
.sort({ [sort]: soringOrder })
.skip(+skip)
.limit(+limit)
.exec();
}
};
module.exports = mongoose.model('product', ProductScema);