
function toLower(v) {
  return v.toLowerCase();
}

const mongoose = require('mongoose'); // An Object-Document Mapper for Node.js
//const assert = require('assert'); // N.B: Assert module comes bundled with NodeJS.
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) => {
    //assert.equal(null, err);
    console.info('เพิ่มรายการติดต่อใหม่สำเร็จ');
    db.disconnect();
  });
};
const getContact = (name) => {
  // Define search criteria
  const search = new RegExp(name, 'i');
  Contact.find({$or: [{fname: search }, {lname: search }]})
  .exec((err, contact) => {
    //assert.equal(null, err);
    console.info(contact);
    console.info(`ค้นเจอทั้งหมด ${contact.length} รายการ`);
    db.disconnect();
  });
};
//exports.toLower = lower
module.exports = {addContact,getContact};
