Sign In Register

How can we help you today?

Start a new topic
Answered

Javascript problem

Hi,

I've made a collection named ‘UserInfo’ which contains following:

{
 "playerId": "571eccf3f528a1ccf4a19”,
 "inven": {
    "snCounter": 0,
    "chars": {}
  }
}


In cloud code,

var playerId = Spark.getPlayer().getPlayerId();
var col = Spark.runtimeCollection( "UserInfo" );
var doc = col.findOne( {"playerId":playerId} );

var newSn = ++doc.inven.snCounter;               // newSn is 1
var newChar = { "sn":newSn, "rank":1, "lv":1 };
doc.inven.chars[ newSn ] = newChar;               // assigned ‘undefined’

col.update(
        { 'playerId':playerId },
        { '$set':
            {
                'inven' : doc.inven
            }
        },
        false,
        false ); 

when I trace above code in debug mode, doc.inven.chars[ “1” ] is undefined.

I don’t understand why it can’t be assigned.



one more thing,

doc.inven.chars = { “1” : newChar };      // it works!
delete doc.inven.chars[ newSn ];           // nothing happened


Please help me...



Best Answer

Hi Lee,


We're looking into this odd behavior in further detail as it seems like findOne() returns a JSON doc that doesn't like to be changed.


In the meantime one workaround is to Stringify the doc returned then create a new JSON doc by parsing this string.


 

var doc = col.findOne( {"playerId":playerId} );
var updatedDoc = JSON.parse(JSON.stringify(doc)) 

 

This should allow you to alter the updatedDoc the way you want.


If you have any other questions let me know,


Pádraig




Thanks Lee,


We're looking into this.


Oisin

Answer

Hi Lee,


We're looking into this odd behavior in further detail as it seems like findOne() returns a JSON doc that doesn't like to be changed.


In the meantime one workaround is to Stringify the doc returned then create a new JSON doc by parsing this string.


 

var doc = col.findOne( {"playerId":playerId} );
var updatedDoc = JSON.parse(JSON.stringify(doc)) 

 

This should allow you to alter the updatedDoc the way you want.


If you have any other questions let me know,


Pádraig



Update:


As I suspected It’s a bug similar to one we fixed previously (https://support.gamesparks.net/helpdesk/tickets/1775).
Basically if you use a key that is an integer value (even if it’s passed in as a string) the engine running the Cloud Code does some weird stuff with it.


This is being fixed next release. In the meantime, please use the workaround.


Thanks,


Pádraig

Login to post a comment