skip to Main Content

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);
    }
  });
});

3

Answers


  1. Chosen as BEST ANSWER

    well solved question it turns that let Depart = mongoose.model("depart", departSchema); will automatically create a table in plural form which means is this case it will create departs so to avoid this problem we need to add more parameters to it so it will be let Depart = mongoose.model("depart", departSchema,"depart");


  2. 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)
    }
    
    Login or Signup to reply.
  3. 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);
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search