简体   繁体   English

如何仅从 Nodejs 中的数据库列值返回值

[英]How return only value from Database column value in Nodejs

I have created a function to return the Database column value.我创建了一个 function 来返回数据库列值。 The function returns value well. function 的返回值很好。 But it is not the format that I want.但这不是我想要的格式。 I have explained my problem below by code.我在下面通过代码解释了我的问题。

Function: 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 -->以上function返回值是这样的-->

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.您可以清楚地看到您的note变量当前包含一个包含 1 object 的数组,并且 object 具有您想要返回的notes_html属性。

First, you need to access the object which you do by: note[0] .首先,您需要通过以下方式访问 object: 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 .其次,您只想获取该 object 的notes_html的属性,这可以通过: note[0]['notes_html']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您的结果是一个 JSON 对象数组,带有一个键notes_html

To access this result, you can get the first element of the note array using array indexing note[0]要访问此结果,您可以使用数组索引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']然后,要专门访问 object 中的密钥,您可以传递密钥以使用note[0]['notes_html']检索值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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