简体   繁体   中英

Nodejs async await function JSON

I have a little probleme. I want send in my res.json in classes: postQuery.room. But it's send in classes: undefined, why?

ROUTE GET

app.get('/', async function (req, res) {
   const pageSize = +req.query.pagesize;
   const page = +req.query.page;
   if (pageSize && page) {
       postQuery = await Classe.find({}).skip(pageSize * (page - 1)).limit(pageSize);
   }
   const nbClasses = await Classe.count({});
   res.json({ success: true, message: "Classes fetched successfully!", classes: postQuery.room, total: nbClasses });
});

postQuery return if I use in res.json => classes: postQuery

{
   "success": true,
   "message": "Classes fetched successfully!",
   "classes": [
       {
           "_id": "5bfd26072b9d9c33005b58c2",
           "room": "NodeJs",
           "createdAt": "2018-11-27T11:09:59.077Z",
           "updatedAt": "2018-11-27T11:09:59.077Z",
           "__v": 0
       }
   ],
   "total": 11
}

I think you've missed that

await Classe.find(...)...

returns an array, note the square brackets in your response. What may be helpful is:

{..., classes: postQuery.map(a=>a.room), ...}

Hope this helps.

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