Reputation: 1588
In one nodeJS (node1) application I created a businessSchema:
import mongoose from "mongoose";
const Schema = mongoose.Schema;
const businessSchema = new Schema({
name: {
type: String,
required: true
}
},
{timestamps: true});
const Businesses = mongoose.model<BusinessModel>("Businesses", businessSchema);
export default Businesses;
In the other nodejs application (node2) I created campaignSchema that has ref to the Businesses schema:
import mongoose from "mongoose";
const Schema = mongoose.Schema;
const campaignSchema = new Schema({
promotion: {
type: String,
required: true
},
business: {
type: Schema.Types.ObjectId,
required: false,
ref: "Businesses"
},
},
{timestamps: true});
const Campaigns = mongoose.model<CampaignModel>("Campaigns", campaignSchema);
export default Campaigns;
when I tried to fetch the campaign (from node2)
async findById(id: string) {
const campaign = Campaigns.findOne({ _id: id })
.populate("business")
.exec();
return campaign;
}
I get this error: MissingSchemaError: Schema hasn't been registered for model "Businesses". Use mongoose.model(name, schema)
This error has not occurred when used monolith (one application) Also, this error obviously has not occurred when removing the populate()
I looked here:https://stackoverflow.com/a/47038544/3083605 which did not help because it is multiple connections from the same application and the models and schema declared in the same connection or process which is not my case
Upvotes: 1
Views: 925
Reputation: 3719
You need to pull your schemas out into an external dependency if you want to use them with both applications. Application 2 has no idea what a "Businesses" model is, because node.js needs to have that schema parsed as part of application 2. Application 1 is running in a different process, so they are independent of each other.
You can take your mongoose models, and any of the files that you're importing to be used by the models, and put them in a separate directory. Then you can set that directory up to be an npm module, hosted from git or bitbucket, and add it to the package.json for both applications.
Upvotes: 3