How to promisify Mongo/Mongoose find

与世无争的帅哥 提交于 2020-06-01 05:06:07

问题


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

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.

Query:

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

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

Edit

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


回答1:


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


来源:https://stackoverflow.com/questions/62072195/how-to-promisify-mongo-mongoose-find

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!