[英]MongoDB : does Collection.Find() support promise
I was trying to revamp an old Nodejs web service to replace callback functions with chained promises. 我正在尝试改造旧的Node.js Web服务,以用链式Promise代替回调函数。 When querying mongodb we used the syntax below to iterate through a result set.
查询mongodb时,我们使用以下语法遍历结果集。
collection.find(filter).toArray(function(err, items) {
if (err) {
throw(err);
} else {
console.log(items);
}
If I try to replace the .toArray()
section with a .then()
I get the below error "col.find(...).then is not a function". 如果我尝试更换
.toArray()
与部分.then()
我收到以下错误:“col.find(...),然后是不是一个函数”。
If I replace .find()
with .findOne().then()
, the code works perfectly. 如果我将
.find()
替换为.findOne().then()
,则代码可以正常工作。
Any help is appreciated. 任何帮助表示赞赏。
find
returns a Cursor
, but the cursor's toArray
method returns a promise. find
返回一个Cursor
,但是光标的toArray
方法返回一个promise。 So you can do: 因此,您可以执行以下操作:
collection.find(filter).toArray().then(...)
I assume you're using mongoosejs. 我假设您正在使用mongoosejs。
collection.find() is just a query. collection.find()只是一个查询。 To cause it to execute and return a promise, you need to call .exec() on it.:
为了使它执行并返回一个promise,您需要在其上调用.exec()。
collection.find(filter).exec()
.then(items => console.log(items))
.catch(err => { // handle error })
The mongoose docs give you more details on how to use mongoose with either callbacks or promises: https://mongoosejs.com/docs/api.html#model_Model.find 猫鼬文档为您提供了有关如何在回调或Promise中使用猫鼬的更多详细信息: https : //mongoosejs.com/docs/api.html#model_Model.find
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.