I'm trying to add user to my users collection in MongoDB. I'm using mongoose with NodeJS and Typescript, and when I try to run the project, I get the error:
The 2nd parameter to `mongoose.model()` should be a schema or a POJO
at Mongoose.model
The error states that the problem is in this file:
import { Router, Request, Response } from "express";
const UserType = require("../enums/UserType");
const UserSchema: mongoose.Schema = require("../schemas/UserSchema");
import mongoose from "mongoose";
import { v4 as uuidv4 } from "uuid";
export class UserRouter {
router: Router;
private userSchema = mongoose.model("UserSchema", UserSchema, "Users");
constructor() {
this.router = Router();
this.init();
}
init() {
this.router.post("/create", this.createUser);
}
//@ts-ignore
async createUser(req: Request, res: Response) {
const uid = uuidv4();
const info = req.body;
var user = new this.userSchema({
uid: uid,
username: info.username,
password: info.password,
type: UserType.User,
});
console.log(user);
}
}
const userRouter = new UserRouter();
const router = userRouter.router;
export default router;
UserSchema is of type mongoose.Schema<any>, when hovering on it with the pointer, this is what pops up: const UserSchema: mongoose.Schema<any>
This is my UserSchema:
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema({
uid: {
type: String,
required: true,
unique: true,
},
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
type: {
type: Number,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("UserSchema", UserSchema);
Why do I keep getting this error message, even though it seems like the error should not be present?
The reason why you get this error is you declared the mongoose model in a recursive way: mongoose.model(UserSchema,mongoose.model(),"Users") in your code. You should export UserSchema instead of creating a schema model and exporting it. your code should look like this:
module.exports.UserSchema = UserSchema; In the other module you could import the schema :
const {UserSchema} = require("../schemas/UserSchema"); and eventually create a new model of the schema in the UserRouter class:
private userSchema = mongoose.model("UserSchema", UserSchema);
It is possible to get the same error if you define mongoose.model() twice for the same schema:
import mongoose from 'mongoose';
const { Schema } = mongoose;
const blogSchema = new Schema
const UserSchema = new mongoose.Schema // delete new......
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With