Home > Software engineering >  User.create is not a function in mongoDB
User.create is not a function in mongoDB

Time:08-30

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;

CodePudding user response:

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;

CodePudding user response:

Your model file please update with the following code snip

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 },
}, { collection : 'UserData'});

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

module.exports = User;
  • Related