1

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

2
  • 2
    mongoose will create a collection on MongoDB using a plural name of the model name(default behavior). So your model bear is pointing to the bears collection. That's why you are getting data from bears collection. Commented Sep 21, 2018 at 12:42
  • 1
    By default your collection names will be appended with extra 's' and hence your bear collection will be bears. Check your database collections by show collections Commented Sep 21, 2018 at 12:43

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.