User.create is not a function in mongoDB

Issue

I’m learning the MERN stack and trying to create an authentication, but now I have a problem, whenever I’m trying to register, I have an error ‘TypeError: User.create is not a function’.
I think that I have a problem with user model or export. Please help

INDEX.JS

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const dotenv = require("dotenv");
const app = express();
const User = require("./models/User");
dotenv.config({ path: "./.env" });

app.use(express.json());
app.use(cors());

mongoose.connect(process.env.MBD_CONNECT, { useNewUrlParser: true }, (err) => {
  if (err) return console.error(err);
  console.log("Connected to MongoDB");
});

app.post("/api/registr", async (req, res) => {
  console.log(req.body);
  try {
    const user = await User.create({
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      email: req.body.email,
      password: req.body.password,
    });
    res.json({ status: "ok" });
  } catch (err) {
    console.log(err);
    res.json({ status: "error", error: "Duplicate email" });
  }
});

app.post("/api/login", async (req, res) => {
  const user = await User.findOne({
    email: req.body.email,
    password: req.body.password,
  });

  if (user) {
    return res.json({ status: "ok", user: true });
  } else {
    return res.json({ status: "error", user: false });
  }
});

app.listen(3001, () => {
  console.log("SERVER RUNS PERFECTLY!");
});

USER.JS (MODEL)

const mongoose = require("mongoose");

const User = new mongoose.Schema({
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
});

const model = mongoose.model("UserData", User);

module.exports = User;

Solution

You’re exporting the schema, not the model. create is a method of mongoose Model class, see document here.

const model = mongoose.model("UserData", User);

module.exports = User; // <------ problem here

It should be:

const model = mongoose.model("UserData", User);

module.exports = model;

Answered By – Đăng Khoa Đinh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published