What's stopping me from being able to "map" this collection of mongooses?

I have been attempting to map a group of user documents within mongoDB. Here's the code snippet I've written for this purpose.

User.retrieveUsers = 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")
        }
    })
}

After examining the code, it appears that instead of mapping the array as intended, it only displays the original data stored.

Answer №1

Utilizing the map function of an array results in a fresh array being generated after the application of the designated mapping function to each individual element. Reassigning it back to the users variable should rectify the issue, as both the console.log and Promise resolve call will then be utilizing the newly formed array:

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

According to the information provided by MDN:

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

Answer №2

Array.map is a method that generates a new array. To use map, remember to assign the resulting array to users.

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

Alternatively, you can achieve the mapping through a projection, where you specify the fields you want to receive from the database. In mongoose, this process may look like the following:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the div on the current page using externally retrieved information

Once again, I find myself stuck on a problem. Allow me to explain. Within this div, I have retrieved data using HTML SIMPLE DOM from another site. Like so: <div id="data">.....</div> Currently, the data refreshes whenever the user reloads th ...

A singular Vuejs Pinia store utilizing namespaced actions

Is it possible to separate pinia actions into two distinct namespaces, allowing access through properties n1 and n2 like this: // current store.n1a('hi') store.n2b() // wanted store.n1.a('hi') store.n2.b() // cumbersome workaround: sto ...

Automatically navigate to a specific element as the user scrolls down the page

I am attempting to achieve a similar effect as seen on the App Builder Website. When the user reaches the header with the background image/video and scrolls down, the website smoothly transitions to the next div/section. If the user scrolls back up and ret ...

Conditional rendering of a component in ReactJS while maintaining the "empty" space

Is there a way to conditionally render a component without affecting the layout of other components? I'm trying to avoid unwanted shifts caused by this div https://i.sstatic.net/g1eUd.gif Do you have any suggestions? Here is a snippet of my code: ...

Tips on how to turn off HTTPS-only fetch requests in Expo React Native/Node.js

Recently, I encountered an issue while attempting to use the fetch API to communicate with my localhost server. The fetch request resulted in the following error: [Unhandled promise rejection: TypeError: Network request failed] - node_modules\whatwg- ...

Slide containing Ionic list views

In my Ionic app, I am using ion-slide-box with 3 slides. Each slide contains an ion-list (table view) with varying numbers of items. The issue is that when scrolling through the shorter list items, it shows empty content due to the taller sibling list taki ...

Problem arising from reduxjs/toolkit - unable to execute action dispatch

As I delve into learning React, focusing on reactjs/toolkit in this specific section, I am working through a series of basic examples to enhance my understanding. One particular example involves simulating a user logging into their account. Despite identif ...

My wish is for the animation to activate when hovering over an "a" element on the progress bar

Below is the HTML and CSS code: .collection-by-brand { position: relative; display: flex; width: 100%; height: auto; justify-content: space-around; flex-wrap: wrap; background: linear-gradient(to bottom, #ffffff, whitesmoke); margin-bo ...

Unable to establish a connection with the default port on Mongo DB while utilizing Node.js

I am new to using Node.js and I'm trying to establish a connection with MongoDB in my Node.js application, but I'm encountering issues. Here is the code snippet: var mongo = require("mongodb"); var host="127.0.0.1"; var port=mongo.Connection.DE ...

Utilizing JavaScript to transition a grayscale thumbnail image to vibrant color

I am a beginner in the world of web development and I have no idea how to begin coding a JavaScript function that will smoothly transition a grayscale thumbnail image into a color thumbnail image when the user hovers their mouse over it, and then back to g ...

Encountered a MongoNetworkError while attempting to establish a connection with the server at localhost:27017. The initial connection failed due to an ECONNREFUSED error at 127.0.0.1:

Encountered a MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017 If I reinstall MongoDB, the code works fine. However, I am looking for a permanent solution. [error:MongoNetworkE ...

The method you are trying to call is not defined in Laravel

I recently developed a basic CRUD blog application with tags functionality. I have integrated tags into my pages and implemented the use of Select JS for selecting and editing tags in input fields. Now, my goal is to have the input field pre-populated wit ...

Animating CSS when closing a modal box

I followed the instructions from a tutorial on W3Schools here to create this code. The "open model" button triggers the modal to open with a smooth CSS animation, which looks great. However, when I click the close button, the modal abruptly closes without ...

Not all databases are retrieved in the search query

When I make an API call to get all the Database entries, I am encountering an issue. The response I receive only includes a few databases instead of all of them. async function checkDatabases(item){ if(item.object == 'database') ...

Utilize ZLIB and Node.js to create a compressed zip archive of a folder's contents

I need to compress all the files in a directory into a single ZIP file. Currently, I am using this code snippet: var fs = require('fs'); var tar = require('tar'); var zlib = require('zlib'); var path = require('path&apo ...

Error in Node.js (NPM Error)

Recently, I purchased a VPS running Ubuntu 14.4 and successfully installed Node.js 1.4. However, when attempting to run my script (node tradebot.js), I encountered the following error message! :-/ module.js:327 throw err; ^ Error: Cannot find ...

What's causing the unexpected rendering outcome in Three.js?

Here is a mesh created in Blender: https://i.sstatic.net/KBGM5.jpg Upon loading it into Three.js, I am seeing this result: https://i.sstatic.net/PCNQ8.jpg I have exported it to .obj format and ensured all faces are triangulated. I am not sure why this is ...

When a JSON response contains an array of objects with only one element, it is received as a single object

When sending a response from my resource as an array of objects, I encounter an issue where if the array only contains one element, the response is transformed into a single object instead of an array with one object, preventing me from looping through it. ...

Identifying flex-wrap capabilities across different browsers

Currently, I am developing a project that involves implementing a responsive grid using the flex wrap property. However, since my project needs to support IE9 and older versions of Firefox (version 28 and below), I am in need of a way to determine their ...

Validation of Date in Angular 5 (with specified minimum and maximum dates)

Struggling to find a simple solution for this issue, I have a date input like the following: <input [(ngModel)]="toolDate" type="text" class="tool_input tool_input__date"> To control the input and restrict it to only accept dates, I am using . In m ...