2014-02-10 66 views
0

我的模式是:MongooseJS獨特的組合指數

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}); 

我想的SKU爲每CLIENT_ID唯一的。所以我認爲這個指數可以做到這一點。我運行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 

我在做什麼錯?

+0

你可以試試嗎? var secondItem = JSON.parse(JSON.Stringify(validItem));我的猜測是您的原始引用在'validItem.save'之後失效' – Kiran

回答

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(); 
    }); 
    }); 
}); 
+0

仍然收到錯誤: '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' – Shamoon