Home > Software design >  Mongoose Schema Export - User is not a constructor
Mongoose Schema Export - User is not a constructor

Time:04-01

I've been stuck on this problem for a long time and have no clue what's the problem as everything seems to be all right. Here's the code that I'm trying:

index.js

const express = require('express')
require('./db/mongoose')
const User = ('./models/user')

const app = express()
const port = process.env.PORT || 3000


app.use(express.json())

app.post('/users', (req, res) => {
    const user = new User(req.body)

    user.save().then(() => {
        res.send(user)
    }).catch(() => {

    })
})

app.listen(port, () => {
    console.log('The server is up and listening on port '   port)
})

user.js

const mongoose = require('mongoose');
const validator = require('validator');

const User = mongoose.model('User', {
    email: {
        type: String,
        required: true,
        trim: true,
        lowercase: true,
        validate(value) {
            if (!validator.isEmail(value)) {
                throw new Error('Email is invalid')
            }
        }
    },
    
    name: {
        type: String,
        required:  true,
        trim: true
    },

    password: {
        type: String,
        required: true,
        trim: true,
        minlength: 7,
        validate(value) {
            if (value.toLowerCase().includes('password')) {
                throw new Error('Password cannot be password - Please enter a different password')
            }
        }
    },
    age: {
        type: Number,
        default: 0,
        validate(value) {
            if (value < 0) {
                throw new Error('Age must be a positive number')
            }
        }
    }
});

module.exports = User

When I try to fetch data from Postman using the URL localhost:3000/users it gives me an error which says, TypeError: User is not a constructor

I'm sure that there's a problem with the mongoose schema, especially at the line where it declares const user = new User() but I have no clue that why is it a problem as it seems like that I have not made any mistake any typo.

I'd appreciate if someone could help me out here. My file system is like this:

Task-Manager
   /src
      index.js
      /db
         mongoose.js
      /models
         user.js

CodePudding user response:

I think it is because you have to use a mongoose schema when creating the model, like so:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    // Your definition of properties and validators go here
    email: {
        type: String,
        unique: true,
    },
    password: String
});

const User = module.exports =  mongoose.model('User', UserSchema)

Also, you can use use the model like this:

const User = mongoose.model('User');

CodePudding user response:

The error was due to typo. On line 3 in index.js, I forgot to add 'require'

const User = ('./models/user')
  • Related