1

I can not get data from my MongoDb collection via mongoose - I'm getting an empty array out of my request. It only happens when I'm using a route which I posted below. Code

router.get("/options", async (req,res) => {
  try {
    const { animalClass} = req.body;
    if (!animalClass) {
    const animalClasses = await AnimalClass.find({});
    console.log(animalClasses);

    return res
      .status(200)
      .json({animalClasses})

    } else {
      const animalTypes = await AnimalType.find({class: animalClass});
      console.log(animalTypes);

      return res
        .status(200)
        .json({animalTypes})
    }

  } catch (err) {
    res
      .status(500)
      .json({msg: err})
  }
});

Schema

const mongoose = require('mongoose');

const animalClassSchema = new mongoose.Schema({
  name: {type: String, required: true}
})

module.exports = AnimalClass = mongoose.model('animalClass',animalClassSchema);

insomnia req

mongoDB collection

console

Casper222
  • 101
  • 2
  • 9
  • 1
    By default, Mongoose pluralizes your collection name. That might be what's happening. Can you verify? Try specifying your collection name, like in this answer: https://stackoverflow.com/a/7527515/1520071 – MattM Oct 18 '20 at 18:04
  • This is so weird, but it worked :B – Casper222 Oct 18 '20 at 20:49
  • Yeah, one of the pitfalls of ORMs :) sometimes they try to do too much for you. I posted an answer since you confirmed that was the issue. – MattM Oct 18 '20 at 21:13

1 Answers1

1

Specify the collection name when creating the schema, like:

const animalClassSchema = new mongoose.Schema({
  name: {type: String, required: true}
}, { collection: 'animalClass' });

By default, Mongoose pluralizes your collection name. This option allows you to override that behavior. More info in the docs:

https://mongoosejs.com/docs/guide.html#collection

MattM
  • 1,159
  • 1
  • 13
  • 25