【问题标题】:Mongoose do something after "model.findById" in nodeMongoose 在节点中的“model.findById”之后做一些事情
【发布时间】:2017-10-16 12:41:10
【问题描述】:

我正在使用 mongoose 遍历节点中的一组用户。我想将每个用户的数据保存在一个 excel 文件中。

    Usr.findById(usrID, function(err, foundTagestipp){
        sheet1.set(1, counter, 'some Userdata');
    }

问题是我想在文件通过整个集合后保存文件。

那么我什么时候知道最后一个用户完成的时间?我可以以某种方式将其提供给回调,还是可以在完成后以某种方式从 mongoose 获取信息?

我希望我的意思很清楚...... 抱歉问了个小问题

【问题讨论】:

标签: node.js mongodb mongoose callback


【解决方案1】:

您可以将每个异步调用包装在一个 Promise 中,收集一个 Promise 列表并通过调用 Promise.all() 在循环外解决它们,然后执行您的业务逻辑。

let promises = [];
myCollection.forEach(elem => {
 let promise = new Promise( (resolve, reject) => {
   Usr.findById(elem.usrID, function(err, foundTagestipp){
      if(err) {
        return reject(err);
      }
      resolve({userId: elem.usrId, userData: foundTagestipp})
    }
 })
 promises.push(promise);
})

Promise.all(promises)
.then(data => {
   //here all the findById have already been called
   //you can save your data to the csv 
 })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多