someRandomSerbianGuy
someRandomSerbianGuy

Reputation: 491

Pushing object into globally declared array in Node.js

I never used global variables in Node.js so I have trouble understanding why this wont work. I am declaring global variable that is array, than I want to push some object into it and for sake of debugging I just want to stringify it. I tried it like this:

var test = require('./api/test'); //my class
global.arrayOfObjects = []; //declaring array
global.arrayOfObjects.push = new test(123); //docs3._id is something I return from db
console.log(JSON.stringify(global.arrayOfObjects)); //I get []

Upvotes: 1

Views: 2397

Answers (2)

developer_hatch
developer_hatch

Reputation: 16224

You must do one of this three, you are mixin both:

var test = require('./api/test'); 
//global.arrayOfObjects = []; not need to declare the var here
global.arrayOfObjects = new test(123); from db
console.log(JSON.stringify(global.arrayOfObjects));

or

var test = require('./api/test'); 
global.arrayOfObjects = []; //needed to declare with this option
global.arrayOfObjects.push(1);
global.arrayOfObjects.push(2);
global.arrayOfObjects.push(3);
console.log(JSON.stringify(global.arrayOfObjects));

or

global.arrayOfObjects.push(new test(123)); // I think this is the best option

Upvotes: 0

rafascar
rafascar

Reputation: 343

You have to pass the object you want to push into the array as an argument:

global.arrayOfObjects.push(new test(123));

Array.prototype.push() documentation

Upvotes: 5

Related Questions