【问题标题】:MongooseJS Unique combination IndexMongooseJS 唯一组合索引
【发布时间】:2014-02-10 03:12:15
【问题描述】:

我的架构是:

var ItemSchema = new Schema({
  sku: {
    type: String,
    trim: true,
    index: true,
    required: true
  },
  description: {
    type: String,
    trim: true,
    required: true
  },
  client_id: {
    type: Schema.ObjectId,
    ref: 'Client',
    index: true,
    required: true
  }
}, {versionKey: false, autoIndex: false});

ItemSchema.index({sku: 1, client_id: 1}, {unique: true});

我希望每个 client_id 的 sku 都是唯一的。所以我认为索引可以解决问题。我正在运行mocha 单元测试,测试是:

  it('should fail if the sku is not unique per client', function(done) {
    var secondItem = validItem;
    return validItem.save(function(err) {
      should.not.exist(err);
      return secondItem.save(function(err) {
        should.exist(err);
        done();
      });
    });
  });

保存第二个项目(相同的sku 和相同的client_id)应该会导致错误。但是,我没有收到任何错误:

  1) <Unit Test> Model Item: Method Save should fail if the sku is not unique per client:
     Uncaught AssertionError: expected null to exist

我做错了什么?

【问题讨论】:

  • 你能试试这个吗? var secondItem = JSON.parse(JSON.Stringify(validItem));我的猜测是您的原始参考在validItem.save 之后失效

标签: express mongoose mocha.js


【解决方案1】:

您的测试失败,因为您没有将两个具有相同skuclient_id 的文档保存到数据库中,而是将相同 文档保存到数据库中两次。

尝试创建一个新文档并从有效项目中复制skuclient_id

it('should fail if the sku is not unique per client', function(done) {
  var secondItem = new Item({
     sku: validItem.sku,
     client_id: validItem.client_id,
     description: 'Put whatever you want here'
  });
  return validItem.save(function(err) {
    should.not.exist(err);
    return secondItem.save(function(err) {
      should.exist(err);
      done();
    });
  });
});

【讨论】:

  • 还是报错:Uncaught AssertionError: expected { [MongoError: E11000 duplicate key error index: my-test.items.$client_id_1_sku_1 dup key: { : ObjectId('52f80e8643bb1a0000ebfd5c'), : "ABC123" }] name: 'MongoError', err: 'E11000 duplicate key error index: my-test.items.$client_id_1_sku_1 dup key: { : ObjectId(\'52f80e8643bb1a0000ebfd5c\'), : "ABC123" }', code: 11000, n: 0, connectionId: 443, ok: 1 } to not exist
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 2012-03-24
  • 2014-10-01
  • 2016-11-30
  • 2018-08-15
  • 1970-01-01
相关资源
最近更新 更多