Reputation: 65
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
Reputation: 51881
You can use findOne
method instead of limiting your query results:
Payments
.findOne({ ... })
.sort({ ... })
.then(result => {
// ...
})
Upvotes: 1
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