Home > Back-end >  get does not return the data in express
get does not return the data in express

Time:08-26

I'm working with a simple GET request but it returns nothing in the browser with no warnings. I checked all the connections to Mongoose works perfectly and collection name are correct.

const uriAtlas = "mongodb://localhost:27017/appfullMern";

mongoose.connect(uriAtlas).then(() => 
  console.log("successful connexion DB")
);

const Schema = mongoose.Schema;

let departSchema = new Schema(
  {
    code: Number,
    name: String,
  },
  { versionKey: false }
);

let Depart = mongoose.model("depart", departSchema);

app.get("/",  (req, res) => {
  Depart.find({}, (err, results) => {
    if (!err) {
      res.send(results);
    }
  });
});

CodePudding user response:

Please try and wrap the code in a try-catch, but also you're only returning a response if no error. This is bad error handling, as errors or response will bug silently.

try { 
  const Schema = mongoose.Schema;
  let departSchema = new Schema(
  {
    code: Number,
    name: String,
  },
  { versionKey: false }
  );
  let Depart = mongoose.model("depart", departSchema);


  app.get("/",  (req, res) => {
    Depart.find({}, (err, results) => {
      if (!err) {
        res.send(results);
      } else {
        console.log(err)
      }
    });
  });
} catch (error) {
  console.log(error)
}

CodePudding user response:

First of all, make sure the request you are making to your app returns with a 200 status. This way you can discard that the problem is with the request per se and not with the response being empty.

Also, consider using async/await syntax instead. Please refactor your code like so and check again:

  app.get("/", async (req, res) => {
    const results = await Depart.find({});
    res.send(results);
  });
  • Related