user824624
user824624

Reputation: 8068

key duplicates in the array in mongodb even using $addToSet

I have a schema like this schema

{
    'cr':[
              { key: 'key1', value:['value1','value2','value3'] },
              { key: 'key2', value:['value4','value5','value6'] }
         ]
}

function addCriteriaKey(id,key,callback){
    var options = { new: false ,select:'_id'};
        Model.update({'uid':id},{'$addToSet':{'cr':{'key':key}}},options,function(err,data){
           if(err) callback(err,null);
           else callback(null,data);
        })  
}

function addCriterialValueToKey(id,key,value,callback){
    var options = { new: false ,select:'_id'};
        Model.update({'uid':id,'cr.key':key},{'$addToSet':{'cr.$.val':value}},options,function(err,data){
            if(err) callback(err,null);
            else callback(null,data);
        })  
}

so here is my two methods to add a key and add a value, they all works, however the database has one existing key, but I added a extra key, $addToSet doesn't to work anymore.

For example when I have done this:

1. addCriteriaKey('id','abc',function(err,data){})

2. addCriterialValueToKey('id','abc','111',function(err,data){})

the data becomes like

{
    'cr':[
              { key: 'abc', value:['111'] }              
         ]
}

but when I added key 'abc' again. 1. addCriteriaKey('id','abc',function(err,data){})

the data becomes like

{
    'cr':[
              { key: 'abc', value:['111'] },
              { key: 'abc' }                
         ]
}

it seems the $addToSet doesn't work anymore , What I should do to prevent this situation?

Upvotes: 3

Views: 1715

Answers (1)

Shreyance Jain
Shreyance Jain

Reputation: 944

$addToSet checks whole object not a perticular value only so in your case

{ key: 'abc', value:['111'] } 
and
{ key: 'abc'}

both are different for $addToSet

if you want to ensure unique key then you should create a unique index for that like this.

db.collection.ensureIndex( { 'cr.key': 1 }, { unique: true } );

Upvotes: 6

Related Questions