从mongoose查询返回到父函数

时间:2017-12-12 18:09:31

标签: node.js asynchronous mongoose callback

我有一个函数,它接受一串用户名,用逗号分隔它们,然后检查数据库中是否存在该用户名,如果是,则将其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是异步的。如何使用返回导出函数的返回来返回用户ID的数组?

1 个答案:

答案 0 :(得分:0)

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

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))

}

...然后你可以处理返回的promise,你可以使用这样的函数:

// 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
  })

我希望这会有所帮助。