Search code examples
meteormeteor-autoformmeteor-collection2

Meteor aldeed collections2 update data to array of objects using for loop


Hello Now i have a problem. I want to insert data to array of objects using for loop

fields:{
        type:[Object],
        label:"Fields",
        optional:true
    },
    "fields.$.category":{
        type:String,
        label: "Category"
    },
    "fields.$.sub":{
        type:String,
        label:"Sub Category",
    },

And using savaData.js in server i tried

// ServiceProviders.update({
                    //  '_id':"GmkGSXjyNFshomdCu"}, 
                    //  {
                    //      '$set': {'fields':{
                    //              '$.category':categorydata,
                    //              '$.sub':subdata
                    //      }}
                    //  },function(error,result){console.log(error);console.log(x+y);});

and

ServiceProviders.update(
{'_id': 'JN4mRPfJZqBadZtPY' },
    {'$set': {'fields.0.category': categorydata,'fields.0.sub':subdata}},
     true );

then

 var x = "fields."+i+".category";
                    var y = "fields."+i+".sub";
                    x=x.toString();
                    y=y.toString();
    ServiceProviders.update( 
    {'_id': 'JN4mRPfJZqBadZtPY' },
    {'$set': {x: categorydata,y:subdata}},
     true );

I got Different errors every time could you please help me in this issue


Solution

  • Currently, $ Does not work on Meteor js. So you have to create a fields object on either server side or client side:

    var fieldsData = []
    for (var i = 0; i < categorydata.length || i < subdata.length ; i++ ){
        fieldsData.push({
           category : ( categorydata[i] ? categorydata[i] : '' ),
           sub : ( subdata[i] ? subdata[i] : '' )
        })
    }
    
    ServiceProviders.update( 
        {'_id': 'JN4mRPfJZqBadZtPY' },
        {'$set': {fields : fieldsData}},
         true );
    

    Please make sure for either every filds data have cat and subcat value or make cat and subcat cat optional true.