retrieve all users from the mongodb database

How can I modify this function to retrieve all users? I am currently in the process of learning async await and struggling with understanding how to access the request body. Here's my function:

export const get: Operation = async (
  req: express.Request,
  res: express.Response
) => {
  commonUtility.showRequestParam(req);


  let users: db.IUserDocument[] = [];
  try {
    // Add explanation for fetching and storing data from MongoDB here.
    users = await UserModel.find()
      .then(data => {
        return data;
      })
      .catch(err => {
        throw err;
      });
  } catch (err) {
    // Handle errors.
    api.responseError(res, err);
  }

  if (users.length < 1) {
    // What should happen in this case?
    api.responseJSON(res, 200, []);
  }
};

Here is my user model:

export const usersSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  BaseFields
});

export const UserModel = mongoose.model<db.IUserDocument>('Users', usersSchema);

Answer №1

It is not necessary to utilize .then when employing both async and await

export const fetch: Operation = async (
  request: express.Request,
  response: express.Response
) => {
  commonUtility.displayRequestParams(request);
  let usersData: db.IUserDocument[] = [];
  try {
    usersData = await UserModel.find();
    api.sendJSONResponse(response, 200, usersData);
  } catch (error) {
    // Handle error.
    api.sendErrorResponse(response, error);
  }  
};

To learn more about using async await, visit -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

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

FlowRouter's inability to fetch from collection on visiting route can become problematic when attempting to reload the page

In my Meteor + React app, I have defined a route as shown below. My goal is to fetch the post and pass it into a component via props. However, when I reload the page on that URL, I receive an error stating that the post is undefined. Strangely, I can visit ...

Obtain a controller's reference from a callback by utilizing TypeScript

Implementing a simple controller that utilizes a directive/component and passes a function as binding. However, when the function is called, there is no reference available to access any of the controller class services. Within the "public onTileClicked" ...

Error Encountered When Running JavaScript Code

Running the code on my Localhost:3000 is resulting in an error message: Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'id') The specific section of the code causing this error is highlighted in the Source part: ...

Sliding an image from the left side to the right, and then repeating the movement from left to right

I am currently working on a CSS effect for some images. My goal is to have an image appear from the left side, move towards the right side, then reappear from the left and repeat this cycle. I managed to achieve this using the code below: @keyframes sli ...

Using Spring to consume a REST service with dynamic JSON fields

After receiving a JSON request from JavaScript to update a MongoDB collection, I found that part of the JSON was mapped to my Java class (Person), but the inner JSON had dynamic field names. I decided to map the dynamic fields to a JsonObject instead, but ...

After selecting "ok" on the JavaScript alert dialog, the webpage will automatically refresh, causing all information entered into the textboxes to be erased

<?php include "dbconfig.php"; session_start(); ?> <!DOCTYPE html> <html> <head> <title>Log in</title> <link rel="stylesheet" type="text/css" href="styles.css"> <link rel="stylesheet" type="text/css" href="bo ...

Ways to incorporate useEffect within a function or the other way around

Currently, I am facing an issue with my code. I have a function that handles the onChange event to retrieve the input value. Additionally, I have another function that searches for items in an array based on the value from the input and then renders a comp ...

I am having trouble with my jQuery datatable Ajax call - instead of reaching the server, I am seeing an alert indicating

Looking for help with my web page. I have a table that needs to be populated using AJAX calls to the server-side method. I've implemented jQuery DataTables, and here's the code snippet: $(document).ready(function() { $("#tableUserList").DataTa ...

Ways to display additional information in typeahead using Angular JS

Currently, I am using the Bootstrap directory typeahead in Angular. I am looking to display more results in my HTML template instead of just the name: typeahead="job as job.name for job in getJobPlace($viewValue) | filter:{name:$viewValue}" I would like ...

Search for all dictionaries within a given list that include a particular discipline name, then retrieve the specific data from each dictionary

I've been working on this dataset for a while now, but I'm struggling to get the results I need. Can someone help me find the specific data I'm looking for? Below is a sample of my data in JSON format. I want to extract all disciplines that ...

Utilizing Typescript/React to Invoke Microsoft Graph Function and Validate M365 Group Owners

As a newcomer to React and TypeScript, I am eager to utilize the Microsoft Graph API in my React/TypeScript application to verify if the logged-in user is an owner of an M365 group. This is the code snippet I currently have: import { callMsGraph } from ...

`How to retrieve query parameters using the GET method in AngularJS`

I have created a REST API in WSO2 ESB. Below is the request service for the POST method: createUser: function(aUser) { var myCreateUserRequest = { "User": { "UserName": aUser.Username, ...

Encountering issues with ng-repeat in the third iteration

Having Trouble with ng-repeat on the Third Loop (Third Level) <div ng-repeat="child in jdata.children"> <div ng-repeat="childsub in child.children"> <div ng-repeat="text in childsub.text"> {{ text.va ...

Finding the x and y coordinates of a rotated 3D cube using JavaScript

In my quest to create a 3D cube using separate div elements, I am faced with a challenge. Imagine a cube made up of 3*3*3 divs where each div has: X, Y, Z coordinates in the 3D space Rotation angles around the X and Y axes With this information, I shoul ...

Is it possible to invoke a function for every post when within a findById route in Express?

I am currently working on implementing a feature in a blog that showcases all posts with the same tag as the one selected by a user. Below is the code for my show route, which displays the post based on its ID: // SHOW router.get("/:id", function(req,res){ ...

How can scripts communicate with one another through passing arguments?

"scripts": { "dev": "npm run development", "development": "run-something", .... When invoking my script, I use the following command: npm run dev This is a convenient shortcut that executes the standard command npm-run-development. Is there ...

Incorporate a prefix into the URL of Angular development servers

When our application is in production, it will not be served from the root. Instead, it will be served from something like https://ourdomain.com/ourapp. This setup is causing problems with image URLs. To work around this issue, I am trying to serve the ap ...

Learn how to implement drag-and-drop functionality in React by making a component

I am currently experimenting with dragging a component using the react-dnd library. I wanted to replicate functionality similar to this example, specifically only focusing on dragging at the moment. In my application, I have imported and utilized the rea ...

Modify mouse pointer when an object is clicked using JavaScript

Greetings, I am in the process of designing a website for a client. I have encountered a challenge in changing the cursor icon when a user performs a mousedown on an object. There is an image on the webpage When the user clicks on the image, the cursor s ...

Exploring the dynamic changes in user authentication state with Angular Fire subscriptions

At the moment, I have been listening to authentication state changes in my ngOnInit method of my AppComponent: export class AppComponent implements OnInit { constructor(public fireAuth: AngularFireAuth) { } ngOnInit(): void { this.fireAuth.auth ...