简体   繁体   中英

How to return an object instead of an array? (mysql with node,js)

Hey so quick and short I just started using mysql today and I grasped creating a table, inserting rows in that table, querying rows, updating and deleting etc.. But I cant figure out how to return an object if im returning a single object.

for example:

I want to return an object like this

{title: 'object1', body: 'this is object number 1'}

instead it returns

[{ title: 'object1', body: 'this is object number 1 }]

I am usedto using mongodb with mongoose and when I used

collection.findOne I got an object if I used collection.find I got an array

So must I always return an array instead of object with mysql? I have heard of WITHOUT_ARRAY_WRAPPER I tried using it like this

 let query = `SELECT * FROM posts WHERE id=1, WITHOUT_ARRAY_WRAPPER`;

 connection.query(query, (err, results, feilds) => {
     if(err) throw err;
     //etc...
 });

But I get a syntax error stating "ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WITHOUT_ARRAY_WRAPPER' at line 1"

If anyone can help shine some light on this would be greatly appreciated.

If you know that the returned response will always be a single object, then it's easy to return the first index of the array. Instead of return response , we can do return response[0] , right??

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