【问题标题】:How to fetch data from mongo db using get method in express js?如何使用 express js 中的 get 方法从 mongo db 中获取数据?
【发布时间】:2019-02-25 20:57:27
【问题描述】:

我在mongo db 中创建了两个集合bear 和bears。我已经在 express 代码中定义了熊集合,但它正在访问熊数据。我现在很困惑。 (bear 和 bears 具有相同的字段(first_name 和 last_name)但值不同。

这是我的代码

app.js

router.get('/api/bears', (req, res) => {
   console.log("dfgdg",req.body)
    Bear.getBears((err, bear) => {
        if(err){
            throw err;
        }
        console.log("fdggfd",bear);
        res.json(bear);
    });
});

models/bear.js

const mongoose = require('mongoose');


const bearSchema = mongoose.Schema({
    first_name:{
        type: String,
        required: true
    },
    last_name:{
        type: String,
        required: true
    },
    create_date:{
        type: Date,
        default: Date.now
    }
});

const Bear = module.exports = mongoose.model('Bear', bearSchema);


module.exports.getBears = (callback, limit) => {
    Bear.find(callback).limit(limit);
}

谁能知道为什么取熊数据而不是熊?

【问题讨论】:

  • mongoose 将使用模型名称的复数名称在 MongoDB 上创建一个集合(默认行为)。所以你的模型熊指向熊系列。这就是您从熊收集中获取数据的原因。
  • 默认情况下,您的收藏名称将附加额外的“s”,因此您的熊收藏将是熊。通过show collections 检查您的数据库集合

标签: javascript node.js mongodb collections


【解决方案1】:

我试过你的代码也遇到了同样的问题,我通过在mongoose.model中添加第三个参数来修复它,指定集合的​​名称

const Bear = module.exports = mongoose.model('Bear', bearSchema, 'bear');

祝你好运

【讨论】:

    【解决方案2】:

    您可以使用mongoose.model 中的第三个参数作为集合名称,例如

    //following will fetch the from bear collection
    const Bear = module.exports = mongoose.model('Bear', bearSchema, 'bear');
    
    
    //following will fetch the from bears collection
    const Bear = module.exports = mongoose.model('Bear', bearSchema, 'bears');
    

    来自文档

    当没有传递集合参数时,Mongoose 使用模型名称。 如果您不喜欢这种行为,请传递集合名称,使用 mongoose.pluralize(),或者设置你的模式集合名称选项。

    参考https://mongoosejs.com/docs/api.html#mongoose_Mongoose-model

    【讨论】:

      猜你喜欢
      • 2020-04-22
      • 2020-11-20
      • 2014-12-01
      • 1970-01-01
      • 2015-01-22
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多