ruby
ruby

Reputation: 65

Destructuring first Array item or How to force Mongoose to return Object instead of 1-item Array

Mongoose's .find method returns Array even if one result is found, its logical

But for example i know for sure that result is 1-item or empty Array

How can i destructure result or beg mongoose to do that?

Payments
  .find({ ... })
  .sort({ ... })
  .limit(1)
  .then(result => {
    result = result[0]; // need to write more conditions, this may throw an exception when array is empty
  })

Upvotes: 2

Views: 741

Answers (2)

madox2
madox2

Reputation: 51881

You can use findOne method instead of limiting your query results:

Payments
  .findOne({ ... })
  .sort({ ... })
  .then(result => {
    // ...
  })

Upvotes: 1

Estus Flask
Estus Flask

Reputation: 222865

This case isn't specific to Mongoose.

It can be:

.then(results => {
  if (results.length) {
    const [result] = results;
    ...
  }
});

Or:

.then(([result]) => {
  if (result) {
    ...
  }
});

Both ways are valid in Mongoose, because a result is expected to be truthy if it exists.

Upvotes: 1

Related Questions