2017-12-12 13 views
0

사용자 이름 문자열을 쉼표로 분리 한 다음 해당 사용자 이름이 데이터베이스에 존재하는지 확인하고 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의 배열을 반환하면서이 작업을 수행하려면 어떻게해야합니까?

답변

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

} 

을 ... 그리고 당신이이 같은 기능을 사용하여 반환 약속을 처리 할 수 ​​

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

도움이되기를 바랍니다.