Home > Mobile >  How can I query my database and return all user documents?
How can I query my database and return all user documents?

Time:06-09

I'm trying to test an API that returns all user documents in Mongo DB, however it keeps returning an empty result. I can't seem to figure out where my code is going wrong.

here's 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 my api for returning 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("Interal server error: "   e.message);
  }
});

when testing this in soap, i keep getting this result in the console. I have one document currently, but it acts like it doesn't exist

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

CodePudding user response:

If you want to use async await you can just simplify your code like this:

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