You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Node.js中Mongoose如何设置多字段联合唯一约束

How to Add a Compound Unique Constraint to Mongoose Schema

Hey there! To set up a compound unique constraint for the user_id and material_id pair (instead of making each field unique individually), you'll need to add a compound unique index to your Mongoose schema. Here's the adjusted code:

const MySchema = new Schema({
  created: { type: Date, default: Date.now },
  updated: { type: Date },
  user_id: { type: Schema.ObjectId, ref: "User", required: true },
  material_id: { type: Schema.ObjectId, ref: "Material", required: true },
  data: { }
});

// Create compound unique index on user_id + material_id
MySchema.index({ user_id: 1, material_id: 1 }, { unique: true });

What this does:

This tells MongoDB to enforce that no two documents can have the exact same combination of user_id and material_id. Unlike setting unique: true on each field separately, this allows:

  • The same user_id to be paired with multiple different material_ids
  • The same material_id to be paired with multiple different user_ids
  • But prevents duplicate pairs (e.g., you can't have two documents where user_id: ObjectId("123") and material_id: ObjectId("456"))

Important notes:

  • If your collection already has existing documents with duplicate user_id + material_id pairs, creating this index will fail. Make sure to clean up any duplicate entries first before adding the index.
  • For existing schemas, you'll need to sync the index with your database. You can do this by calling MyModel.syncIndexes() (replace MyModel with your actual model name) or enable autoIndex: true when connecting to MongoDB (though auto-indexing is not recommended for production environments—manual index management is safer).

内容的提问来源于stack exchange,提问作者SkyDancer

火山引擎 最新活动