Categories
JavaScript Answers

How to fix the ‘schema hasn’t been registered for model’ error with Mongoose?

Spread the love

Sometimes, we want to fix the ‘schema hasn’t been registered for model’ error with Mongoose

In this article, we’ll look at how to fix the ‘schema hasn’t been registered for model’ error with Mongoose.

How to fix the ‘schema hasn’t been registered for model’ error with Mongoose?

To fix the ‘schema hasn’t been registered for model’ error with Mongoose, we should call require on the model files we created.

For instance, we write

/models/Posts.js

const mongoose = require('mongoose');

const PostSchema = new mongoose.Schema({
  title: String,
  link: String,
  upvotes: {
    type: Number,
    default: 0
  },
  comments: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment'
  }]
});

mongoose.model('Post', PostSchema)

to create the PostSchema and register it as 'Post' with the mongoose.model method.

Then we register the models after we connect to the database with

db.js

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/news');
require('./models/Posts');

to call require with './models/Posts' to run the code in /models/Posts.js which registers the model Post model so we can use it.

Conclusion

To fix the ‘schema hasn’t been registered for model’ error with Mongoose, we should call require on the model files we created.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *