问题
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
回答1:
You are getting this error because the find() method is asynchronous, that's why the promise is pending: it is still fetching.
db.collection('diseases').find({
'ttl.txt': {
$regex: data,
$options: 'i'
}
}).toArray().then((data) => {
// Here you can do something with your data
doSomethingWithTheResult(result)
})
Notice that you have your data inside a callback. For more info about promises check Promise
Depending on your node version (7.6+ I believe), you can use something like this
async function getResults() {
return db.collection('diseases').find({
'ttl.txt': {
$regex: data,
$options: 'i'
}
}).toArray();
}
const results = await getResults();
So your code with look like a synchronous code. The key here is the async/await command that wait for the promise results.
Hope it helps!
回答2:
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);
}
});
回答3:
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);
});
来源:https://stackoverflow.com/questions/45198268/mongodb-cursor-toarray-returns-promise-pending