Home > Net >  MongoDB, collection name appears to be wrong
MongoDB, collection name appears to be wrong

Time:08-11

When I try to call this request

const presidentModel = require('./modules/president.js')

app.get('/president', (req, res) => {
    presidentModel.find({}, (err, result) => {
        if (err) {
            console.log(err) 
        } {
            console.log(result)
        }
    })
})

It only returns an empty array [] then it creates a new collection with the name 'presidents'

enter image description here

Here is my Schema

const mongoose = require("mongoose")

const presidentSchema = new mongoose.Schema({
    nickname: {
        type: String,
        required: true
    },

    fullname: {
        type: String,
        required: true,
    },

    votes: {
        type: Number,
        required: true
    }
})
const president = mongoose.model("president", presidentSchema)
module.exports = president

The request should return the data on collection "president" but what it does is it creates a new collection with the name "presidents". I don't know where is it coming from tho

enter image description here

CodePudding user response:

it is good practice to have your collections as plural, and therefore mongoDB implicitly tries to make collections plural (as there are multiple items to be stored in them).

To override this, you can pass a third parameter to .model() with the name of the collection:

const president = mongoose.model("president", presidentSchema, "president")
  • Related