You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在两个Express后端服务器间共享MongoDB的Mongoose Schema?

How to Share Mongoose Schemas Across Multiple Express Backends

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:

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:

  1. Create a shared schema directory: Make a new folder (e.g., shared-mongoose-schemas) outside your two backend projects.
  2. Initialize it as an npm package: Run npm init inside the folder, fill in basic details (a name like @your-project/shared-schemas is a good convention).
  3. 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
    
  4. Write your shared schemas: Create files like user.schema.js in 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;
    
  5. 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's package.json)

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:

  1. Create a new Git repo for your shared schemas, push your schema files to it.
  2. 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
    
  3. 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 peerDependencies entry in your shared module’s package.json to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 21:22:44