如果我有这样的架构:
var person = new Schema({
firstName: String,
lastName: String,
});
Run Code Online (Sandbox Code Playgroud)
我想确保只有一个文件具有相同的firstName和lastName.
我怎么能做到这一点?
Joh*_*yHK 90
您可以使用index模式调用来定义唯一的复合索引:
person.index({ firstName: 1, lastName: 1}, { unique: true });
Run Code Online (Sandbox Code Playgroud)
我最近才通过对猫鼬的实验发现了有趣的小东西。我有以下架构示例:
const ShapesSchema = new mongoose.Schema({
name: { type: String, required: true },
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
})
ShapesSchema.index({ name: 1, user: 1 }, { unique: true })
mongoose.model('Shapes', ShapesSchema)
Run Code Online (Sandbox Code Playgroud)
这个想法是要创建一个在其上name和user在一起唯一的复合索引。这样,只要每个形状都有不同的名称,用户就可以创建任意数量的形状。倒数也应该是正确的-形状可以具有相同的名称,只要它们具有不同的用户即可。对于我来说,效果不佳。
我注意到的是,除了索引之外_id,还创建了其他三个索引条目。分别用于name,user和name_user所有设置是唯一的。我对模式进行了修改,并将其包含unique: false在我用于复合索引的每个字段中,突然所有的工作都按预期进行。我最终得到的是:
const ShapesSchema = new mongoose.Schema({
name: { type: String, required: true, unique: false },
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', unique: false }
})
ShapesSchema.index({ name: 1, user: 1 }, { unique: true })
mongoose.model('Shapes', ShapesSchema)
Run Code Online (Sandbox Code Playgroud)
望着创建的索引,结果我还看到三个指标- name,user和name_user。但是不同之处在于,前两个设置为复合,而前两个设置为唯一。现在,我的用例是每个用户具有多个不同的形状,或者具有不同用户的名称相同的形状就像冠军。
| 归档时间: |
|
| 查看次数: |
20182 次 |
| 最近记录: |