简体   繁体   中英

How return only value from Database column value in Nodejs

I have created a function to return the Database column value. The function returns value well. But it is not the format that I want. I have explained my problem below by code.

Function:

async function getHtmlNoteContent(quote_id){
  try{
   const connection = await mysql.createConnection(config.mysql.credentials);
   const [note] = await connection.query(`select notes_html from table where id = ${quote_id}`);
   connection.end();
   console.log('ppppp -->',JSON.stringify(note));
   return JSON.stringify(note);
  }catch (e) {
    utils.error500(req, res, e.message);
  }
}

above function return value like this -->

ppppp --> [{"notes_html":"<p>column value</p>"}]

But I want -->

ppppp --> <p>column value</p>

Can someone show me how can I do this? Thank you

You can clearly see that your note variable currently holds an array with 1 object and that object has a property of notes_html that you want to return.

First, you need to access the object which you do by: note[0] . Second, you want to get only the property of notes_html of that object which can do by: note[0]['notes_html'] or note[0].notes_html .

So, instead of:

return JSON.stringify(note);

do this:

return note[0].notes_html; // or note[0]['notes_html']

Your result is an array of JSON objects with a single key notes_html

To access this result, you can get the first element of the note array using array indexing note[0]

To then specifically access the key within the object you want, you can pass the key to retrieve the value with note[0]['notes_html']

Producing the line console.log('ppppp -->',note[0]['notes_html']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM