I’m encountering an issue where I’m receiving the error “User.create is not a function” in my Node.js application using Mongoose, despite having what appears to be a correctly defined schema. Here’s my userModel.js:
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema(
{
fullName: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
role: {
type: String,
enum: ["user", "worker", "admin"],
default: "user",
},
password: {
type: String,
required: true,
select: false,
},
passwordConfirm: {
type: String,
required: true,
},
passwordChangedAt: Date,
passwordResetToken: String,
passwordResetExpires: Date,
active: {
type: Boolean,
default: false,
select: false,
},
},
{
timestamps: true,
}
);
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) return next();
this.password = await bcrypt.hash(this.password, 12);
this.passwordConfirm = undefined;
next();
});
userSchema.pre("save", function (next) {
if (!this.isModified("password") || this.isNew) return next();
this.passwordChangedAt = Date.now() - 1000;
next();
});
const User = mongoose.model("User", userSchema);
Additionally, here’s my service code:
const { validationResult } = require("express-validator");
const User = require("../controllers/userController");
exports.register = async (req, res) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
errors.throw();
}
const newUser = await User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
passwordConfirm: req.body.passwordConfirm,
passwordChangedAt: req.body.passwordChangedAt,
role: req.body.role,
});
console.log(newUser);
res.send(201).json({
status: "success",
data: {
user: newUser,
},
});
} catch (err) {
res.status(400).json({
status: "fail",
message: err.message,
});
}
};
My requested body looks fine:
{
"fullName": "Super Name",
"email": "[email protected]",
"password": "Aa12345@",
"passwordConfirm": "Aa12345@"
}
I’m also wondering if there’s a way to restrict the submission of the “role” field during user registration, considering it defaults to “user”.
And if thre is a way to throw 400 status code based on validationResult, but also trow 500 status code it catch block for internal server error?
Truly i have nothing in my mind what should i try, because in my opinion userModel looks fine. I tried to restart server, but of course it didn’t help.
Danis Bikmeev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.