-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongoose.3.js
69 lines (59 loc) · 1.57 KB
/
mongoose.3.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
// p44 运行: node mongoose.3.js
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const url = 'mongodb://localhost:27017/mongoose-test-db';
mongoose.connect(url, {useNewUrlParser: true});
const bookSchema = mongoose.Schema({ name: String });
bookSchema.method({
buy (quantity, customer, callback) {
var bookToPurchase = this;
console.log('buy');
return callback();
},
refund (customer, callback) {
console.log('refund');
return callback();
}
});
bookSchema.static({
getZeroInventoryReport (callback) {
console.log('getZeroInventoryReport');
let books = [];
return callback(books);
},
getCountOfBooksById (bookId, callback) {
console.log('getCountOfBooksById');
let count = 0;
return callback(count);
}
});
let Book = mongoose.model('Book', bookSchema);
Book.getZeroInventoryReport(() => {});
Book.getCountOfBooksById(123, () => { });
let practicalNodeBook = new Book({ name: 'Practical Node.js, 111' });
practicalNodeBook.buy(1, 2, () => { });
practicalNodeBook.refund(1, () => { });
bookSchema.post('save', function (next) {
console.log('post save');
return next();
});
bookSchema.pre('remove', function (next) {
console.log('pre remove');
return next();
});
practicalNodeBook.save((error, results) => {
if (error) {
console.error(error);
process.exit(1);
} else {
console.log('Saved: ', results);
practicalNodeBook.remove((error, results) => {
if (error) {
console.error(error);
process.exit(1);
} else {
process.exit(0);
}
})
}
})