'MongoDB: cursor.toArray returns Promise { <pending> }
Situation
I wrote a query:
var results = db.collection('diseases').find({
'ttl.txt': {
$regex: data,
$options: 'i'
}
}).toArray();
Problem
Then I printed results to a console.
if (results.length > 0) {
console.log(results);
}
ToArray method must return array of found documents. But this method returns me this string: Promise { <pending> }.
Question
How can I return array of found documents instead of this string?
PS
toArray: Link to the documentation
Solution 1:[1]
In the toArray() method you write a callback function:
var results = db.collection('diseases').find({
'ttl.txt': {
$regex: data,
$options: 'i'
}
}).toArray(function(err, result) {
if (results.length > 0) {
console.log(results);
}
});
Solution 2:[2]
The error is giving because it's a promise
var results = db.collection('diseases').find({
'ttl.txt': {
$regex: data,
$options: 'i'
}
}).lean().then(function (obj) {
if (!obj) {
return resolve('not find');
}
return resolve(obj);
}).catch(function (err) {
return reject(err);
});
Solution 3:[3]
A modern approach using async/await. In this case, we want to get matching bird colors in the birds collection.
async function getBirdsByColor(color) {
try {
var birds = await db.collection('birds').find({
color: color
}).toArray()
if(!birds || !birds.length) {
throw('No birds with color: ' + color)
}
console.log('Successfully found one or more birds:', birds)
} catch (e) {
console.log('Bird search failure: ', e)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kaspar Lee |
| Solution 2 | jcardoso |
| Solution 3 | Ankur Soni |
