Home > OS >  mongoose.model() method returning undefined
mongoose.model() method returning undefined

Time:09-04

Trying to find a mongoDB entry using the .findOne method, but it returns the following error:

TypeError: Cannot read properties of undefined (reading 'findOne')

I feel that this has got something to do with the .models/.model method in my schema file since I'm not receiving any compile info, i.e returning undefined type. I'm likely doing something wrong, so any help pointing it out would be appreciated - Thank you

Schema file:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const banSchema = new Schema({
    userId: {
      type: Number,
      required: true
    },
    reason: {
      type: String,
      required: true
    },
    period: {
      type: String,
      required: false,
      default: 'permanent'
    }
})

const name = 'Ban'
//
console.log(typeof(mongoose.models[name] || mongoose.model[name, banSchema])) // Undefined
//
module.exports = mongoose.models[name] || mongoose.model[name, banSchema]

CodePudding user response:

You should be exporting your model like this

module.exports = mongoose.model('Ban', banSchema);

You can read more about it here

  • Related