0

I have a data model which looks like this

{
    _id: 1
    some_property: some_value
    items: [
    {
        item_id: item1
        item_properties: [
        {
            key1: val1,
            key2: val2
        }]
    }]
}

When I get a new item with item_id=itemX, I would like to check if an item with this item_id is in the items array. If it's not present, then insert it. If it is present, i would like to append the item_properties to the existing item_properties.

I tried using $addToSet, but this considers the entire item and not the item_id itself. So the result was 2 items with the same item_id.

Any idea how i can achieve this atomically?

Thanks, Aliza

user1063287
  • 10,265
  • 25
  • 122
  • 218
Aliza
  • 734
  • 1
  • 10
  • 25

1 Answers1

0

The following codes can run atomically, I think.

function doWhenItemExisted() {
    var n = db.c.update({
        "items.item_id" : itemX
    }, {
        $pushAll: { // I think item_properties of given item is also an array
            "items.$.item_properties" : item.item_properties
        }
    }).nModified;
    if (!n) {
        doWhenItemNotExisted();
    }
}

function doWhenItemNotExisted() {
    var n = db.c.update({
        "items.item_id" : {
            $ne : itemX
        }
    }, {
        $push: {
            "items" : item
        }
    }).nModified;
    if (!n) {
        doWhenItemExisted();
    }
}

// entry
doWhenItemExisted();
Wizard
  • 4,341
  • 1
  • 15
  • 13