简体   繁体   中英

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

I have created two collections bear and bears in mongo db. I have defined bear collection in express code but it is accessing bears data. 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

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

Can anyone know why bears data is fetched instead bear??

You can use the third argument in mongoose.model for collection name like

//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. If you don't like this behavior, either pass a collection name, use mongoose.pluralize(), or set your schemas collection name option.

Reference 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

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

Good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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