Search code examples
node.jsmongodbmongoosenosqlnestjs

How to reference a model that's not in project using mongoose


I am building a microservice for Referral System for this existing app which has it's main backend already running. This Microservice will be an add-on to that. I built a Referral Model which is like this :

import mongoose from "mongoose";

const RefSchema = new mongoose.Schema({
    referralID : {
        type : String,
        required : true
    },
    userID : {
        type : mongoose.Types.ObjectId,
        ref : 'Customer',
        required : true
    },
    userStatus : {
        type : String,
        required : true
    },
    linkedAccounts : {
        type : [mongoose.Types.ObjectId],
        ref : 'Customer',
        default : []
    }
},{
    timestamps : true
});

const RefModel = mongoose.model('referrals', RefSchema);
export default RefModel;

Now, As you can see the ref is set to "Customer", which is exactly how it's modelled in the Main server. When I try to populate anything in the referral objects, I get an error from NestJS which says

Schema hasn't been registered for model "Customer". Use mongoose.model(name, schema)

If you have any idea what's gone wrong please let me know, also I looked in the compass, the collection name is "customers", so even by trying that I got the same error.


Solution

  • Try to import the Customer schema before defining the Ref schema, this will initialize the required model.

    Also, you should use mongoose.Schema.Types.ObjectId in Schema declarations:

    import mongoose from "mongoose";
    import Customer from "path/to/customer-schema";
    
    const RefSchema = new mongoose.Schema({
        referralID : {
            type : String,
            required : true
        },
        userID : {
            type : mongoose.Schema.Types.ObjectId,
            ref : 'Customer',
            required : true
        },
        userStatus : {
            type : String,
            required : true
        },
        linkedAccounts : {
            type : [mongoose.Schema.Types.ObjectId],
            ref : 'Customer',
            default : []
        }
    },{
        timestamps : true
    });