K
K
KushchO2019-03-18 11:20:21
JavaScript
KushchO, 2019-03-18 11:20:21

How to convert Cursor from mongodb to json string?

Good afternoon!
Having transformed the cursor using the toArray() method, I got the following array:
[{"_id":"5c8e1a7b11598528844eb695","title":"Perform task","description":"","status":"pending","deadline": ""},{"_id":"5c8e1a7b11598528844eb696","title":"Node.js Classes","description":"Go through the MongoDB database chapter","status":"pending","deadline":" "}]
to get a json string, I want to convert the array to an object, and then apply JSON.stringify
Here from this answer I used the proposed method https://toster.ru/q/517614:
collection.find({}).toArray(function (err,
tasks){ if(err) return console.log(err);
let obj = tasks.reduce((res, el) => ({...res, ...el}), {});
console log(obj);
res.send(tasks);
console.log("Data sent");
})
});
and I get just the last object, not even nested:
{ _id: 5c8e1a7b11598528844eb696,
title: 'Node.js Lessons',
description: 'Go through the MongoDB database chapter',
status: 'pending',
deadline: '' }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2019-03-18
@KushchO

this is how it should be, because the _id title fields, etc. in the object are overwritten, one object cannot have several fields with the same name,
what should the final object look like after reduce?
maybe you just want

collection.find({}).toArray(function(err, tasks){
  if(err) return console.log(err);
  res.send({ tasks });
  console.log("Данные отправленны");
})
});

only then there is no need to toArray at all, you can immediately send an object with the result, for example,
collection.find({}).then(data => res.json(data))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question