faruqhossen30
4/26/2020 - 11:33 AM

mongoose

// ---------------------------------------------
// For get all data like => map()
Model.find()
        .then((contacts) => {
          console.log(contacts)
            res.render('pages/contact', { contacts, errors: {} });
        })
        .catch(error => console.log(error))
        
        
  // ------------------------------------------------
  // ---------------------------------------------
// For get single data
// findOne is use id paramiter as a object property value
// findOne return a object
    const { id } = req.params
    Model.findOne({ _id: id })
        .then((contact) => { // 
            console.log('findOne = type of', typeof contact)
            res.render('pages/singleContact', {contact});
        })
        .catch(error => console.log(error))
  // ------------------------------------------------
  // Update fontact find
exports.updateContact = (req, res) => {
    const {id} = req.params
    Contact.findOne({_id: id})
    .then((data)=>{
        res.render('pages/contact-update', {data});
    })
    .catch(error => console.log(error))
    
}
// Update contact Save
exports.updateSaveContact = (req, res)=>{
    const {id} = req.params
    const {name, email, phone} = req.body
    const updateData = {name, email, phone}

    Contact.findOneAndUpdate({_id:id}, updateData)
    .then((some)=>{
         res.redirect('/contact');
    })
    .catch(error => console.log(error))
}


exports.deleteContact = (req, res) => {
    const { id } = req.params
    Contact.findOneAndDelete({ _id: id })
        .then(() => {
             res.redirect('/contact')
        })
        .catch(error => console.log(error))
}