如何在两个Express后端服务器间共享MongoDB的Mongoose Schema?
Hey there! Dealing with duplicate schema files across separate backend services is such a common frustration—no one wants to remember to sync changes in two places every time you tweak a field. Here are two solid, practical solutions to solve this, with examples you can adapt right away:
Solution 1: Create a Local Shared NPM Module (Recommended)
This is the cleanest approach for long-term maintainability. You'll extract your schemas into a standalone, reusable module that both backends can import.
Step-by-Step Setup:
- Create a shared schema directory: Make a new folder (e.g.,
shared-mongoose-schemas) outside your two backend projects. - Initialize it as an npm package: Run
npm initinside the folder, fill in basic details (a name like@your-project/shared-schemasis a good convention). - Add Mongoose as a peer dependency: Since both backends already use Mongoose, add it as a peer dep to avoid duplicate installs:
npm install mongoose --save-peer - Write your shared schemas: Create files like
user.schema.jsin this folder:// shared-mongoose-schemas/user.schema.js const mongoose = require('mongoose'); const UserSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true }, profilePic: { type: String, default: '/default-avatar.png' }, createdAt: { type: Date, default: Date.now } }); // Optional: Add reusable schema methods UserSchema.methods.getPublicProfile = function() { return { id: this._id, username: this.username, email: this.email }; }; module.exports = UserSchema; - Link the module to your backends:
- In the shared folder, run
npm link - In each backend project, run
npm link @your-project/shared-schemas(use the name you set in the shared module'spackage.json)
- In the shared folder, run
Using the Shared Schema in Your Backends
In both your first and second Express backends, import the schema and create your model (note: models are tied to a Mongoose connection, so you’ll create them separately in each service):
// Backend 1 / Backend 2 - user.model.js const mongoose = require('mongoose'); const UserSchema = require('@your-project/shared-schemas/user.schema'); // Create the model tied to this backend's Mongoose connection const User = mongoose.model('User', UserSchema); module.exports = User;
Now any changes you make to the shared schema will automatically reflect in both backends—no more double-editing!
Solution 2: Use a Git Submodule (For Team Collaboration)
If you’re working with a team and want to keep shared schemas in a dedicated Git repo, use a Git submodule to embed the schema repo into both backend projects.
Step-by-Step Setup:
- Create a new Git repo for your shared schemas, push your schema files to it.
- Add the submodule to each backend:
# In Backend 1 directory git submodule add https://github.com/your-team/shared-mongoose-schemas.git ./shared-schemas # Repeat for Backend 2 - Update submodules when schemas change:
# In each backend, pull the latest schema changes git submodule update --remote
Using the Submodule in Your Backends
Import the schema just like a local file:
const UserSchema = require('./shared-schemas/user.schema'); const User = mongoose.model('User', UserSchema);
Key Notes to Avoid Issues
- Mongoose Version Compatibility: Ensure both backends use the same major version of Mongoose to prevent schema parsing conflicts. Add a
peerDependenciesentry in your shared module’spackage.jsonto enforce this. - Model Creation: Always create models within each backend, not in the shared module—models are bound to a specific Mongoose connection instance, which each backend initializes separately.
- Schema Methods/Plugins: If you add methods, virtuals, or plugins to your shared schema, they’ll work across both backends automatically.
内容的提问来源于stack exchange,提问作者DOYEOP KIM

