【问题标题】:Returning from mongoose query to parent function从猫鼬查询返回到父函数
【发布时间】:2018-05-26 12:20:01
【问题描述】:

我有一个函数,它接受一串用户名,用逗号分隔它们,然后必须检查该用户名是否存在于数据库中,如果存在,则将其 ID 放入一个数组中。

module.exports = function (peopleString) {
let people = peopleString.split(',')
for (person in people) {
    people[person] = people[person].replace(/ /g,'')

    users.findOne({username: people[person]}, function (err, document) 
    {
            if (err) {
                console.log(err);
            }

            if (!document) {
                people.splice(person, 1)
            }

            people[person] = document._id
        })
    }

    return people
}

问题是在进行所有查询之前,函数已经返回,因为 mongoose 是异步的。我如何在仍然使用导出函数的 return 来返回用户 ID 数组的同时完成这项工作?

【问题讨论】:

    标签: node.js asynchronous mongoose callback


    【解决方案1】:

    您可以一次性找到所有匹配的文档并返回承诺:

    module.exports = function (peopleString) {
    
      // Split string into array
      let people = peopleString
        .split(',')
        .map(person => person.replace(/ /g,''))
    
      // Find all users where username matched any value in the array
      // Return a promise which will eventually resolve to an array of ids
      return users
        .find({ username: { $in: people } })
        .then(docs => docs.map(doc => doc._id))
    
    }
    

    ...然后您可以在使用函数的地方处理返回的承诺,如下所示:

    // Import your function
    const getUserIds = require('./get-user-ids')
    
    // Your string of people
    const peopleString = ' ... '
    
    // Call then/catch on the eventual result
    getUserIds(peopleString)
      .then(ids => {
        // Handle results
      })
      .catch(err => {
        // Handle error
      })
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-06-29
      • 2018-03-07
      • 2019-09-29
      • 2023-03-21
      • 1970-01-01
      • 2022-11-22
      • 2016-07-27
      • 1970-01-01
      • 2017-12-03
      相关资源
      最近更新 更多