猫鼬:如何定义一个独特的字段组合?

mar*_*cci 51 mongoose

如果我有这样的架构:

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)

  • 这只对我有用,如果我先放弃我的收藏. (7认同)
  • @chovy您不需要删除集合,但是您需要删除字段上的任何现有复合索引. (4认同)
  • 只有满足唯一要求时才会创建索引.这解释了为什么@chovy必须放弃他的收藏(可能只是删除重复) (4认同)
  • 为了确定哪些重复项阻止了索引的粘连,可以执行以下操作:'Model.on('index',function(err){console.log(err)});` (3认同)
  • 我没有现有的复合索引。但是即使重新启动我的应用服务器后,我也能够(重复地)添加重复项。直到我放下收藏,才开始。 (2认同)
  • 这在第一次尝试时对我有用,而不必以任何其他方式删除或修改集合 (2认同)

lda*_*key 9

我最近才通过对猫鼬的实验发现了有趣的小东西。我有以下架构示例:

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)

这个想法是要创建一个在其上nameuser在一起唯一的复合索引。这样,只要每个形状都有不同的名称,用户就可以创建任意数量的形状。倒数也应该是正确的-形状可以具有相同的名称,只要它们具有不同的用户即可。对于我来说,效果不佳。

我注意到的是,除了索引之外_id,还创建了其他三个索引条目。分别用于nameusername_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)

望着创建的索引,结果我还看到三个指标- nameusername_user。但是不同之处在于,前两个设置为复合,而前两个设置为唯一。现在,我的用例是每个用户具有多个不同的形状,或者具有不同用户的名称相同的形状就像冠军。

  • 这对我帮助很大。我还需要根据此处的文档添加 `mongoose.connect(uri, { useCreateIndex: true });`:https://mongoosejs.com/docs/guide.html#indexes (2认同)