1

Am using the following script to update quotes as escaped characters in strings that are held in a 4 String array and am unable to get the $ifnull to work. Have tried various forms and the latest is:

var myCursor = db.collection.Fence.find( { "properties.d.v" : { $regex : '.*".*'} } );

while (myCursor.hasNext())
{
    printjson( myCursor.next() );
    var fence = myCursor.next();
    var test;

    test = { $ifNull: [ fence.properties.d.v[0], "null" ] }
    print ( "0: ", test );
    $cond: [ { $eq: [ test, "null" ] }, fence.properties.d.v[0], fence.properties.d.v[0].replace( '"', '\"' ) ];
    test = { $ifNull: [ fence.properties.d.v[1], "null" ] }
    print ( "1: ", test );
    $cond: [ { $eq: [ test, "null" ] }, fence.properties.d.v[1], fence.properties.d.v[1].replace( '"', '\"' ) ];
    test = { $ifNull: [ "fence.properties.d.v[2]", "null" ] }
    print ( "2: ", test );
    $cond: [ { $eq: [ test, null ] }, fence.properties.d.v[2], fence.properties.d.v[2].replace( '"', '\"' ) ];
    test = { $ifNull: [ "fence.properties.d.v[3]", "null" ] }
    print ( "3: ", test );
    $cond: [ { $eq: [ test, null ] }, fence.properties.d.v[3], fence.properties.d.v[3].replace( '"', '\"' ) ];

    db.au.com.bluedot.application.model.geo.Fence.update( { _id : fence._id }, fence );
}

Even when the v[1] is null, the test variable still outputs the following from the print statement:

1:  [object Object]

The following error is then returned from the replace statement:

2015-12-24T10:54:14.301+1100 TypeError: Cannot call method 'replace' of null

If there is a better or easier way to find and escape the quotes within MongoDb, would be happy to know.

Roddy
  • 2,018
  • 3
  • 16
  • 21
  • 2
    You can simply `replace` by checking - `if(fence.properties.d.v[0]){//code to replace}`. You need not use `mongoDB` operators for this purpose. – BatScream Dec 24 '15 at 00:27
  • Of course! D'oh. Many thanks for that. – Roddy Dec 24 '15 at 00:38
  • Is there any obvious reason why the fence.properties.d.v[n] is only retrieving the first character of the string? – Roddy Dec 24 '15 at 00:39
  • `fence.properties.d.v` is a *string* ? I assumed it to be an `array`. If it is a string, `v[n]` will give you the character at `n`th position. You could just check - `if(fence.properties.d.v){// code to replace the first and last characters}` – BatScream Dec 24 '15 at 00:42
  • Thanks; was just one of the Strings was a single character (when it is meant to be consistently 7). – Roddy Dec 24 '15 at 00:52
  • Would you like to add your comment as the answer? – Roddy Dec 24 '15 at 00:52

1 Answers1

0

From BatScream in the comments above; you can simply replace by checking

if(fence.properties.d.v[0]){//code to replace}

You need not use mongoDB operators for this purpose.

Community
  • 1
  • 1
Roddy
  • 2,018
  • 3
  • 16
  • 21