如何推广Mongo / Mongoose查找 [英] How to promisify Mongo/Mongoose find

查看:58
本文介绍了如何推广Mongo / Mongoose查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为另一个问题的一部分,我试图推广一个mongo / mongoose查找查询。我在搜索栏中找不到什么帮助。该查询在下面,我正在将此查询作为express中的控制器的一部分运行。设置是route-> userController.monitor,它需要包含查询

As part of another question I am trying to promisify a mongo/mongoose find query. I found little help via the search bar. The query is below, I am running this query as part of a controller in express. Setup is route -> userController.monitor which needs to contain the query

在寻求其他问题的帮助时,我被要求 promisify查找,以便您可以使用await(例如const events = Incident.find({fooID})。exec(); ,尽管SO搜索和我自己尝试使它成真的尝试都失败了。

In getting help for the other question I was asked to promisify find so that you can use await for it (like const incidents = Incident.find({fooID}).exec(); though SO search and my attempts at promisifying it myself have failed.

查询:

Incident.find({fooID})
.exec((err, incidents) => {
// do something
})

请注意,在这种情况下,findOne无法使用,因为几乎所有时间都将返回多个文档

Note a findOne will not work in this case because multiple documents will be returned almost all the time

编辑

Incident.find({monitorID,createdAt:{$ gte:sevenAgo}})

Incident.find({ monitorID, createdAt: {$gte: sevenAgo} })

推荐答案

您可以创建承诺版本使用node.js的 util 模块中的 promisify 函数查找功能

You can create a promisified version of your find function using the promisify function in the util module of node.js

const { promisify } = require('util')

const promisifiedIncidentFindExec = payload => {
  const query = Incident.find(payload)
  return promisify(query.exec).call(query)
}

const incidents = await promisifiedIncidentFindExec({
  monitorID: 'monitorID',
  createdAt: { $gte: 'sevenAgo' },
})
// do something

这篇关于如何推广Mongo / Mongoose查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆