9

I got js file to run within mongodb where I got console.log expression for debugging:

use test;
db.city.find().snapshot().forEach(function(city){
    var Pos = city.Pos;

    if (Pos) 
    {
        longLat = Pos.split(" ");
        console.log("longLat");  // for debugging ----------------------------  
        console.log(longLat);

        lon = longLat[0];
        lat = longLat[1];

        if (lon && lat)
        {
            lon = parseFloat(lon);
            lat = parseFloat(lat);
            longLat = [lon, lat];
            city.longLat = longLat;

        }

    }
    db.orgs.save(city);

})

When I run it...

mongo < /path/to/this/js/file.js

... I got error in the output:

ReferenceError: console is not defined

Is there any way to log intermediate results for debugging purposes?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Maxim Yefremov
  • 13,671
  • 27
  • 117
  • 166

2 Answers2

12

Use the print or printjson methods instead. These are used to emit just like console.log() within the shell:

    if (Pos) 
    {
        longLat = Pos.split(" ");
        print("longLat");  // for debugging ----------------------------  
        printjson(longLat);
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
0

If you don't want to change your code you could do this.

var console = {};
console.log = print;

Then when your code calls console.log, it's actually calling print(). But this is not a true replacement because it doesn't handle printing of objects like NodeJS's console.log() does. For example,

console.log('abc', { 'field1' : 123 });
// In NodeJS output is: abc { field1: 123 }
// In Mongo print output is: abc [object Object]

A more full featured implementation would handle this. This article Taking Over console.log might help if you wanted to create a more full featured implementation.

PatS
  • 8,833
  • 12
  • 57
  • 100