MissingSchemaError: Schema hasn't been registered for model "User, userSchema". Use mongoose.model(name, schema)

Issue

hope you’re doing well.

i’m following a tutorial ( from 2019 ), and i’m facing this error at the moment.

here’s the code. ( let me know if you need anything else )

// index.js //

const express = require('express');
const app = express();
const dotenv = require('dotenv');
const mongoose = require('mongoose');

dotenv.config({ path: "./config.env"});

// Connect to DB
mongoose.connect(process.env.DB_CONNECT,
    () => console.log('connected to db!')
);


// Middleware
app.use(express.json())

// Import Routes
const authRoute = require('./routes/auth');

// Route middlewares
app.use('/api/user', authRoute);

app.listen(3000, () => console.log('server running'));

// User.js //

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        min: 6,
        max: 255
    },
    email: {
        type: String,
        required: true,
        min: 6,
        max: 255
    },
    password: {
        type: String,
        required: true,
        min: 7,
        max: 1024
    },
    date: {
        type: Date,
        default: Date.now
    }
});

module.exports = mongoose.model('User, userSchema')

// auth.js //

const router = require('express').Router();
const User = require('../model/User')

router.post('/register', (req, res) => {
    const user = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password,
    });
});

module.exports = router;

Thank you in advance.

The Lord be with you and save you all, your families and friends 🙂

Solution

I think the problem is here:

mongoose.model('User, userSchema')

you can fix it this way:

mongoose.model('User', userSchema)

so userSchema can define as schema not the name of collection

Answered By – Naime

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.