javascript - 如何在 express js 中使用 get 方法从 mongo db 中获取数据?

标签 javascript node.js mongodb collections

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

这是我的代码

应用程序.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);
    });
});

模型/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.model 添加第三个参数来修复它指定集合的​​名称

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

祝你好运

关于javascript - 如何在 express js 中使用 get 方法从 mongo db 中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52443890/

相关文章:

javascript - 模 % 大数 - 无穷大错误 - Javascript

javascript - JS : Filter array only for non-empty and type of string values

node.js - 如何获取登录用户的对象数组的总和

javascript - 使用动态字段名称更新数据

mongodb - 在 golang 中连接到远程 mongodb 服务器失败,出现身份验证错误

javascript - 确定 JS 插件未收到必需参数时死亡的最佳实践?

javascript - Aurelia 验证未绑定(bind)到文本框组件

javascript - 在 NodeJS 上暂停和恢复 PostgreSQL 连接

javascript - 如何让 npm 包 bin 使用实验模块选项运行?

mongodb - 如何使用 PHP 获取 MongoID 的字符串值?