How to update one or more fields ignoring empty fields in NODE MySQL

Viewed 174

I use MySQL and NodeJS and my objective is to update a profile row. But no matter what field the user will chose to update, the backend should ignore the empty field and update the chosen field.

exports.update = (req, res, next) => {
    const url = req.protocol + '://' + req.get('host');
    let NewURL = req.file.path.split('\\')[1]
    const image = url + '/images/' + NewURL; // req.file.path
    
    let postID = req.params.id;

   let { title, subtitle, content } = req.body;
   //? tilte : oldvalue.title}

   const sql2 = `Select * from posts where post_ID = ${postID}`;

db.query(sql2,  (error, result) =>{
    if (error) throw error;
    
    else {
        console.log(result);

        const sql = `UPDATE posts
        SET 
         post_title          = '${title ? title : result.post_title }' , 
         post_subtitle       = '${subtitle  ? subtitle : result.subtitle }' , 
         post_content        = '${content  ? content : result.content}' , 
         imagesLink          = '${image  ? image : result.image }' 
         WHERE post_ID       = '${postID}'
        `;

        db.query(sql,  (error, result) =>{
            if (error) throw error;
            
            else {
                res.send(result);

            }
        });
    }
})
}

In this function I tried to implement two sql queries and using the ternary operator, replace the old value from the db with the new value. Still, I get the undefined fields in the DB and the backend request that the image is required to be updated...

Can somebody help? Thanks.

0 Answers
Related