Home > Blockchain >  Why am I unable to "map" this mongoose collection?
Why am I unable to "map" this mongoose collection?

Time:09-27

I am trying to map a collection of user documents in mongoDB. Below is my code.

User.getUsers = function() {
    return new Promise(async (resolve, reject) => {
        try {
            let users = await ValidUser.find()
            users.map(function(user) {
                return {
                    username: user.username,
                    email: user.email
                }
            })
            console.log(users)
            resolve(users)
        } catch {
            reject("404")
        }
    })
}

This code just logs the original stored data and doesn't "map" the array at all.

CodePudding user response:

Array.map returns a new array. If you want to use map, you'll need to assign the return array to users.

users = users.map(function(user) {
            return {
                username: user.username,
                email: user.email
            }
        })

The mapping you want to do can also be done through a projection which is when you specify which fields you want to be returned by the database. In mongoose it might look like this:

let users = await ValidUser.find().select({ username: 1, email: 1, _id: 0 })

CodePudding user response:

The map function of an array returns a new array after applying the passed in mapping function to each element. If you assign it back into the users variable, that should correct the issue as the console.log and Promise resolve call will now be using the newly created array:

users = users.map(function(user) {
    return {
        username: user.username,
        email: user.email
    }
})

From MDN:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

  • Related