0

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)

1
  • There a several issues with how you are defining your variables. Does console.log(req.body) print what you expect? Commented Mar 16, 2024 at 14:18

1 Answer 1

0

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);
    };

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.