【问题标题】:Getting an empty array Mongoose获取一个空数组 Mongoose
【发布时间】:2021-02-01 12:43:52
【问题描述】:

我无法通过 mongoose 从我的 MongoDb 集合中获取数据 - 我从我的请求中得到一个空数组。只有当我使用我在下面发布的路线时才会发生这种情况。 代码

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

架构

const mongoose = require('mongoose');

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

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

【问题讨论】:

  • 默认情况下,Mongoose 会将您的收藏名称复数。这可能就是正在发生的事情。你能验证吗?尝试指定您的集合名称,如以下答案:stackoverflow.com/a/7527515/1520071
  • 这很奇怪,但它确实有效:B
  • 是的,ORM 的陷阱之一 :) 有时它们会试图为您做太多事情。我发布了一个答案,因为您确认这是问题所在。

标签: node.js json mongodb rest mongoose


【解决方案1】:

创建schema时指定集合名称,如:

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

默认情况下,Mongoose 会将您的收藏名称复数。此选项允许您覆盖该行为。文档中的更多信息:

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

【讨论】:

    猜你喜欢
    • 2019-04-27
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    相关资源
    最近更新 更多