"Schema hasn't been registered for model" Error in mongoose only while populating

26 Views Asked by At

i am making a project using express and mongoose, i have 3 models (users, blogs, comments). all the queries work fine except populate, it gives me 'Schema hasn't been registered for model'. but:

  1. that error doesn't happen with all models, it actually works with users model only!
  2. when i tried to put the ref in the schema as the model it self ref: User not as string ref: "User" , THE ERROR IS GONE!
  3. i tried to make ref lowercase, put didn't work

i don't know why

and i want to know if it is OK to put ref as the model itself ref: User ?

here is my connection


connect = async () => {
  try {
    const conn = await mongoose.connect(DATABASE_URI);
  } catch (error) {
    console.log(error);
  }
};

here is my user schemas

import mongoose from "mongoose";
import { emailsValidator } from "../utils/emailsValidator";

export const userSchema = new mongoose.Schema(
  {
    username: {
      type: String,
    },
    likes: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Blog",
      },
    ],
  }
);

export default mongoose.model("User", userSchema);

here is my blog schema

import mongoose from "mongoose";
import User from "./userModel";
import Comment from "./commentModel";

export const blogSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      unique: true,
    },
    body: {
      type: String,
    },
    comments: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: Comment,
      },
    ],
    likedBy: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
    ],

  }
);

export default mongoose.model("Blog", blogSchema);

I am using mongoo atlas and nodmon too

thanks

1

There are 1 best solutions below

1
mohamed yousssef On

changing es6 imports to require, solves it!