Search code examples
reactjsmongodbmongoosenext.jsnext.js13

NextJs, ReactJs MissingSchemaError: Schema hasn't been registered for model


I encoutered MissingSchemaError while I was working on a project where I had to make queries on one to many relationship and also .populate() another model objects. Error we are solving in this question: MissingSchemaError: Schema hasn't been registered for model


Solution

  • user.model.ts

    const UserSchema = new Schema({
     name: string, 
     orders: [{
        type: Schema.Types.ObjectId,
        ref: 'Order'
     }]
    });
    const User = models.User || model('User', UserSchema);
    

    order.model.ts

    const OrderSchema = new Schema({
     name: string, 
     user: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true,
        nullable: false,
     }
    });
    const Order = models.Order || model('Order', OrderSchema);
    

    API calls

    import DatabaseConnection from '@/dbConfig/databaseConnection'; // DB connection to DB
    import User from '@/models/user.model'; // User model
    import Order from '@/models/order.model'; // order model
    
    async function getUsersWithOrders() {
     await DatabaseConnection();
     Order; // <~ very important to first register the Orders model first.
     const users = await User.find(queryParams, {createdAt: 0, updatedAt: 0}).populate('orders');
     return users.json()
    }
    

    It is very important to register the relationship model you may want to populate with in the query first before you make the query. That is why we import Order model first before we make query to User model.

    I hope this helps anyone with error: MissingSchemaError: Schema hasn't been registered for model