简体   繁体   English

如何在Express JS中使用get方法从mongo db获取数据?

[英]How to fetch data from mongo db using get method in express js?

I have created two collections bear and bears in mongo db. 我在mongo db中创建了两个collection bear and bears。 I have defined bear collection in express code but it is accessing bears data. 我已经在快速代码中定义了Bear集合,但是它正在访问Bears数据。 I am very confused now. 我现在很困惑。 (bear and bears have the same field(first_name and last_name) but values are different. (熊和熊具有相同的字段(名字和名字),但值不同。

here is my code 这是我的代码

app.js 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 型号/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);
}

Can anyone know why bears data is fetched instead bear?? 谁能知道为什么提取熊数据而不是熊吗?

You can use the third argument in mongoose.model for collection name like 您可以在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');

From the doc 从文档

When no collection argument is passed, Mongoose uses the model name. 如果没有传递任何集合参数,Mongoose将使用模型名称。 If you don't like this behavior, either pass a collection name, use mongoose.pluralize(), or set your schemas collection name option. 如果您不喜欢这种行为,请传递一个集合名称,使用mongoose.pluralize()或设置您的模式集合名称选项。

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

I've tried your code and had the same problem, I fixed it by adding a third parameter to mongoose.model specifies the name of the collection 我已经尝试过您的代码并且遇到了相同的问题,我通过向mongoose.model添加第三个参数来修复了该问题。模型指定了集合的名称

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

Good luck 祝好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM