A
A
Andrew2018-11-25 05:05:39
MongoDB
Andrew, 2018-11-25 05:05:39

Why does MongoDB output an array with an object instead of an object?

This query returns a slightly unexpected result.

app.get('/blog/:url', (req, res) => {
  var db = req.db;
  Post.find({ 'url': req.params.url }, 'title description image content category date url', function (error, post) {
    if (error) { console.error(error); }
    res.send(post)
  })
})

Returns data: Array(1) , that is, an array with the desired object. For this reason, in order to pull out the necessary data, you have to write this.title = response.data[0].title , which seems to me not a very good solution, because hypothetically the index in the array can change.
In the docks, I found only forced casting of the cursor to the toArray() array, but I need it the other way around (

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey, 2018-11-25
@AndrewRusinas

Oh meh. I quickly solved the problem by changing the find method to findOne. Thank you for your attention.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question