Bhakti Thakkar
Bhakti Thakkar

Reputation: 373

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??

Upvotes: 1

Views: 689

Answers (2)

Tariq Saeed
Tariq Saeed

Reputation: 1193

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

Upvotes: 2

Arif Khan
Arif Khan

Reputation: 5069

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

Upvotes: 2

Related Questions