-1

I'm trying to add data to my "data" returned in express. Here my snippet, I'm trying to add currentPage and count variables:

app.get("/blog/page/:pageTargeted", (req,res) => {     
  var rangeScoped = (req.params.pageTargeted * 8);
  Posts.find().sort({ date: -1}).skip(rangeScoped).limit(8).exec(function (err, data) {
    data.currentPage= req.params.pageTargeted || 1 ;
    data.count = Posts.estimatedDocumentCount();
    if (err) return console.error(err);
    console.log(data);
    res.status(200).send(data)
  })
});

I have also tried:

 currentPage= req.params.pageTargeted || 1 ;
 count = Posts.estimatedDocumentCount();
 if (err) return console.error(err);
 console.log(data);
 res.status(200).send(data currentPage, count)

It doesn't works, currentPage and count aren't add in the res.send toward the browser. I have just the data corresponding to the database get's request. So what it going wrong ? I just can't figure out it. Because to me I have well injected the data into the object so, it should works. If anybody has an hint, would be great.

Webwoman
  • 10,196
  • 12
  • 43
  • 87

1 Answers1

1

If I am right data is an array and you can't create a new key in array like that. Try sending an Object instead.

app.get("/blog/page/:pageTargeted", (req,res) => {     
  var rangeScoped = (req.params.pageTargeted * 8);
  Posts.find().sort({ date: -1}).skip(rangeScoped).limit(8).exec(function (err, data) {
    if (err) return console.error(err);
    console.log(data);
    res.status(200).json({data: data, currentPage: req.params.pageTargeted || 1, count: Posts.estimatedDocumentCount()})
  })
});
Suresh Prajapati
  • 3,991
  • 5
  • 26
  • 38
  • great insight, it returns me: TypeError: Converting circular structure to JSON at JSON.stringify () – Webwoman Oct 07 '18 at 10:54
  • yeup, here `send({data: data, currentPage: req.params.pageTargeted || 1, count: Posts.estimatedDocumentCount()})` – Webwoman Oct 07 '18 at 11:12
  • @Webman Try sending with `json`, you can also refer here https://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json/11616993 – Suresh Prajapati Oct 07 '18 at 11:14