What is the process for searching my database and retrieving all user records?

I've been working on testing an API that is supposed to return all user documents from my Mongo DB. However, I keep running into the issue of receiving an empty result every time I test it. I've been struggling to pinpoint where exactly in my code the problem lies.

Here's a snippet of my user model:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let userSchema = new Schema({
  userId: {
    type: String
  },
  pw: {
    type: String
  },
}, {
  collection: "creds"
});
module.exports = mongoose.model("User", userSchema);

And below is the section of my API responsible for retrieving all users:

router.get("/session/users", async (req, res) => {
  try {
    User.find({}, function (err, user) {
      if (err) {
        console.log(err);
        res.status(500).send({
          message: "Interal server error:" + err.message,
        });
      } else {
        console.log(user);
        res.json(user);
      }
    });
  } catch (e) {
    console.log(e);
    console.log(req.body.userId);
    res.status(500).send("Internal server error: " + e.message);
  }
});

Whenever I run this within the SOAP environment, I consistently see the following output in the console. Despite having one existing document, the result seems to suggest otherwise:

Connection to the database instance was successful
[]
GET /api/session/users 200 90.584 ms - 2

Answer №1

To streamline your code using async await, you can implement the following:

router.get("/session/users", async (req, res) => {
    try {
      const users = await User.find({});
      res.json(users);
    } catch (error) {
      console.log(error);
      res.status(500).send("Internal server error: " + error.message);
    }
  });

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

The MatInput value will only display after the page is reloaded or refreshed

After refreshing the page, a matInput field displays a value or result that was previously hidden. https://i.stack.imgur.com/q9LQI.png By selecting or highlighting within the matInput, the value or result becomes visible. https://i.stack.imgur.com/SqaLA.p ...

Best practices for handling HTTP requests in Angular 5

I'm currently developing multiple applications using Angular 5. My aim is to adhere to all the dos and don'ts of Angular. However, I'm facing some confusion regarding a few things. 1) What is the difference between this... this._http.g ...

Manipulating Arrays in Mongoose by Removing an Object and Updating the Others

As a newcomer in the field of web development, I am attempting to create a basic editable image gallery. In order to achieve this, I have established a Collections schema alongside a Paintings schema: var collectionSchema = new mongoose.Schema({ name: ...

Retrieving form data in controller and model through route

Within my app.js file, I am passing the request to the router in the following manner: app.post('/validateUser', validationRoute) In my route, I typically pass the request on to the controller like this, to call the appropriate function: router. ...

Learning about the intricacies of backend Node.js through Angular using GET requests

I am having trouble retrieving the query parameters from a frontend GET request on the backend side. I have attempted to use url and query, but still need assistance fetching the query on the nodejs side. Can someone recommend a method that would allow me ...

Retrieving information from the database and transferring it to the front end via the router

I have been working on a MERN Expo app login and sign-in page. However, I am facing an issue with fetching data from the backend after clicking the sign-in button. Even though I have implemented the find query in the Express router, I am unable to retrieve ...

The click method in the Angular unit test does not seem to be executing successfully

I'm facing a seemingly simple issue where I am unable to confirm that a click handler is being triggered on my component. header.component.ts import { Component, EventEmitter, OnInit, Output } from '@angular/core'; @Component({ selecto ...

Incorporating dynamic data into the main page of NextJs by pulling information from various files

I'm currently facing difficulties while trying to integrate dynamic data from one file into another. The data I am attempting to fetch is located at: path: /src/components/Subnav.js import React, { Component } from "react"; class Subnav ex ...

What steps should be taken to resolve the unauthorized error (401) following a post method in Node.js?

My project involves implementing a login and sign up system. Everything functions correctly in the local environment. Upon registering an account, it is successfully stored in the database. However, attempting to register another account with the same info ...

Contrast between using sendFile('/index.html') versus render('index') with Jade

As a newcomer to JS, I recently stumbled upon a similar question but with a different perspective. So my inquiry is: What are the advantages of using a Jade template in Express over simply sending raw HTML as a response? In other words, why would one choos ...

Using Node.js and Express for sending attachments with Nodemailer

Is there a way to attach a file to an email using Nodemailer that actually works? I've tried various methods following the instructions on , with .pdf, .txt files but nothing seems to be working. Any suggestions or ideas? Here is the code snippet from ...

What is the best way to retrieve comprehensive information from an API?

I have a task to complete - I need to retrieve data from the Pokemon API and display it on a website. This includes showing the name, HP, attack, defense stats of a Pokemon, as well as the Pokemon it evolves into. The challenge I'm facing is obtaining ...

Creating a single definition that encompasses the characteristics of both primitive and generic types without the need for combining them

Here is a scenario where I need to consolidate and refactor two types: ... .then((result1: any) => { let promises = { one: $q.when(val1), two: $q.when(val2) }; return $q.all(promises); }) .then((resolvedPromises: any) => { ...

I am experiencing difficulties in assigning values to a formArray

I am struggling to update values in an array form, as I am facing challenges setting new values. Although I attempted to set values using patch value, my attempts were unsuccessful. // Component.ts this.packageForm = this.formBuilder.group({ title: [&a ...

Having trouble getting anime.js to function properly in an Ionic 3 project?

I have been attempting to incorporate anime.js into my Ionic 3 project, but I keep encountering an error when using the function anime({}) in the .ts file. Error: Uncaught (in promise): TypeError: __webpack_require__.i(...) is not a function TypeError: _ ...

Identifying a shift in data model within a component

It seems like there's a piece I might be overlooking, but here's my current situation - I have data that is being linked to the ngModel input of a component, like so: Typescript: SomeData = { SomeValue: 'bar' } Snippet from the vie ...

Ways to extract single JSON entities from a consolidated JSON structure

I am facing a challenge with parsing multiple JSON objects within a single large JSON object. Currently, the entire JSON object is being stored as one entity, but I need to parse and store them separately in MongoDB. Below is the code snippet I am using. ...

Guide on showing the content of an uploaded file as an object in JavaScript using file reader

When using the file upload function to upload a json file and read its contents, I am encountering an issue where the result is in string format instead of object. How can I display it as an object? Here is my code: .html <div class="form-group"> ...

How to retrieve static attributes while declaring an interface

class A { public static readonly TYPE = "A"; } interface forA { for: A.TYPE } I am facing an issue while trying to access A.TYPE from the forA interface in order to perform type guarding. The error I encounter is: TS2702: 'A' only refe ...

How can I run a TypeScript function within a JavaScript file?

I am working with a typescript file named file1.ts export function Hello(str: string) { console.log(str); } In addition, I have another file called index.js { require('./some.js'); } Furthermore, there is a script defined in the pack ...