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
function toLower(v) {
return v.toLowerCase();
}
const mongoose = require('mongoose');
//const assert = require('assert');
mongoose.Promise = global.Promise;
const db = mongoose.connect('mongodb://localhost:27017/contactdb');
const contactSchema = mongoose.Schema({
fname: { type: String, set: toLower },
lname: { type: String, set: toLower },
phone: { type: String, set: toLower },
email: { type: String, set: toLower }
});
const Contact = mongoose.model('Contact', contactSchema);
const addContact = (contact) => {
console.info(`กำลังเพิ่มรายการติดต่อ ${contact}`);
Contact.create(contact, (err) => {
console.info('เพิ่มรายการติดต่อใหม่ สำเร็จ');
db.disconnect();
});
};
const getContact = (name) => {
const search = new RegExp(name, 'i');
Contact.find({$or: [{fname: search }, {lname: search }]})
.exec((err, contact) => {
console.info(contact);
console.info(`ค้นเจอทั้งหมด ${contact.length} รายการ`);
db.disconnect();
});
};
module.exports = { addContact, getContact };