MongoDB:cursor.toArray返回Promise {< pending> } [英] MongoDB: cursor.toArray returns Promise { <pending> }
问题描述
我写了一个查询:
var results = db.collection('diseases').find({
'ttl.txt': {
$regex: data,
$options: 'i'
}
}).toArray();
问题
然后我将results
打印到控制台.
Problem
Then I printed results
to a console.
if (results.length > 0) {
console.log(results);
}
ToArray方法必须返回找到的文档的数组.但是此方法向我返回了以下字符串:Promise { <pending> }
.
ToArray method must return array of found documents. But this method returns me this string: Promise { <pending> }
.
如何返回找到的文档数组而不是此字符串?
How can I return array of found documents instead of this string?
toArray:链接到文档
推荐答案
您会收到此错误,因为find()方法是异步的,这就是诺言未决的原因:它仍在获取.
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
根据您的节点版本(我认为是7.6+),您可以使用类似的
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();
因此,您的代码看起来像是同步代码.关键是等待诺言结果的async/await命令.
So your code with look like a synchronous code. The key here is the async/await command that wait for the promise results.
希望有帮助!
这篇关于MongoDB:cursor.toArray返回Promise {< pending> }的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!