Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have got a collection aTable with 2 records:

 {
    "title" : "record 1",
    "fields" : [ 
        {
            "_id" : 1,
            "items" : [ 
                1
            ]
        },
        {
            "_id" : 2,
            "items" : [ 
                2,3,4
            ]
        },
        {
            "_id" : 3,
            "items" : [ 
                5
            ]
        }
    ]
},

{
        "title" : "record 2",
        "fields" : [ 
            {
                "_id" : 4,
                "items" : [ 
                    7,8,9,10
                ]
            },
            {
                "_id" : 5,
                "items" : [ 

                ]
            },
            {
                "_id" : 6,
                "items" : [ 
                    11,12
                ]
            }
        ]
    }

I want to update fields aTable.fields.items from

items : [ 11,12 ]

to

items : [ 
   {item: 11, key: 0},
   {item:12, key: 0}
]

I browse fields with forEach but I can't save it:

var t = db.aTable.find();

t.forEach(function( aRow ) {
    aRow.fields.forEach( function( aField ){
        aField.items.forEach( function( item ){
            var aNewItem = { item: parseInt(item), ref: 0 };
            db.aTable.update(item, {$set:aNewItem})
        } )
    } )
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
241 views
Welcome To Ask or Share your Answers For Others

1 Answer

To get what you want you will need a few things:

t.forEach(function( aRow ) {
    var newFields = [];
    aRow.fields.forEach( function( aField ){
        var newItems = [];
        aField.items.forEach( function( item ){
            var aNewItem = { item: parseInt(item), ref: 0 };
            newItems.push( aNewItem );
        } );
        newFields.push({ _id: aField._id, items: newItems });
    } )
    aTable.update(
        { _id: aRow._id }, 
        { "$set": { "fields": newFields } }
    );
});

So basically you need to "re-construct" your arrays before updating


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...