Astrum
Astrum

Reputation: 621

Getting all documents from MongoDB with mongoose

For some reason I'm having a problem getting all documents from MongoDB using mongoose. I want to retrieve all documents and place them into an array for later processing, but this seems to be impossible. Here is the code I'm using:

module.exports = { 
    create: (req, res, next) => {
        // console.log(req.body);
        let userClaim = new UserClaim(getUserParams(req.body));
        let userArr = [];
        UserClaims.find({}).then((users) => {
            users.forEach(user => {
                userArr.push(user);
        });

If I print each user inside the forEach statement, it works. However the array is always empty at the end of the operation. I've stepped through the code with a debugger as well. The array will populate, but return to being empty as soon as the forEach method completes.

Upvotes: 0

Views: 24

Answers (1)

Vikas Keskar
Vikas Keskar

Reputation: 1248

Try following solution,

module.exports = { 
    create: async (req, res, next) => {
        let userClaim = new UserClaim(getUserParams(req.body));
        const userArr = await UserClaims.find({}).lean()
// Print and check userArr
      }

Upvotes: 1

Related Questions