[英]User.create is not a function in mongoDB
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' .我正在学习 MERN 堆栈并尝试创建身份验证,但现在我遇到了一个问题,每当我尝试注册时,我都会遇到错误'TypeError: User.create is not a function' 。 I think that I have a problem with user model or export.
我认为我对用户 model 或导出有问题。 Please help
请帮忙
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;"); });
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;
You're exporting the schema, not the model.您正在导出架构,而不是 model。
create
is a method of mongoose Model
class, see document here . create
是 mongoose Model
class 的方法,请参见此处的文档。
const model = mongoose.model("UserData", User);
module.exports = User; // <------ problem here
It should be:它应该是:
const model = mongoose.model("UserData", User);
module.exports = model;
Your model file please update with the following code snip您的 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 },
}, { collection : 'UserData'});
const model = mongoose.model("UserData", User);
module.exports = User;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.