logic.js 1.48 KB
Newer Older
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
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;


//const db = mongoose.connect('mongodb://localhost:27017/contactdb');  //เชื่อมต่อ กับ database ชื่อ contact-db
mongoose.connect('mongodb://localhost:27017/contactdb');
const db = mongoose.connection;
function toLower(v) {
  return v.toLowerCase();
}

const contactSchema = mongoose.Schema({
  firstname: { type: String, set: toLower },
  lastname: { 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) => {
    //assert.equal(null, err);
    console.info('เพิ่มรายการเชื่อมต่อใหม่สำเร็จ');
    //db.disconnect();
    db.close();
  });
};

const getContact = (name) => {
  // Define search criteria. The search here is case-insensitive and inexact.
  const search = new RegExp(name, 'i');
  Contact.find({$or: [{firstname: search }, {lastname: search }]})
  .exec((err, contact) => {
    //assert.equal(null, err);
    console.info(contact);
    console.info(`ค้นหาเจอทั้งหมด ${contact.length} รายการ`);
    //db.disconnect();
    db.close();
  });
};
// Export all methods
module.exports = {  addContact, getContact };