Tejesh Bheemavarapu
Tejesh Bheemavarapu

Reputation: 3

ReferenceError: User is not defined sovle this problem

const user = require('../modules/User') const express = require('express') const router = express.Router(); router.get('/',(req,res)=>{ console.log(req.body) user = User(req.body); User.save(); res.send(req.body); }

const mongoose = require('mongoose') const { Schema } = mongoose;

const UserSchema = new Schema({ name: { type: String, require: true, }, email: { type: String, require: true, unique: true, }, password: { type: String, require: true, }, date: { type: Date, default: Date.now, }, });

module.export = mongoose.model('user',UserSchema)

Upvotes: 0

Views: 56

Answers (1)

Neeraj Jangir
Neeraj Jangir

Reputation: 63

The error simply means that the User is not defined.Because you are importing it as const user = require('../modules/User');.You should import it as const User = require('../modules/User'); and there are other issues as well in your code.

  1. You should define the model name as User not user in mongoose.model() function , like module.exports = mongoose.model('User',UserSchema);
  2. One suggestion if you don't want to get stuck in these import typos.. Do consider using something like module.exports.User = mongoose.model('User', UserSchema);
  3. Creating an entry in a database is an async operation so you should use async await in your router.get handler .So it will be something like this

const User = require('../modules/User');
const express = require('express');
const router = express.Router();
router.get('/', async (req, res) => {
        console.log(req.body);
        const user = await User(req.body);
        //Now you don't need to save the user it will be saved automatically
        //User.save();
        res.send(user);
    };

Upvotes: 0

Related Questions