TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) JavaScript

Viewed 2507

I have the following code:

    //creates matrix and converts it to JSON file
    var map = JSON.stringify(math.randomInt([10, 10],2));

    //create instance of Map
    const temp= new Map({_id: 2, map: map});
    temp.save(function (err) {
        if (err) return handleError(err);
    
    });

This creates a matrix and puts it into my mongoDB in the Map collection with the following model:

const mapSchema = new mongoose.Schema({ 
    _id: Number,
    map: Array
})
  
const Map = mongoose.model('Map', mapSchema)

And this works fine. but I want to put the whole first snippet into a function, so I can put it in another file, import it in my index.js and there just run this function. So I put a function around it, like so:

const generateMap = function() {
    var map = JSON.stringify(math.randomInt([10, 10],2));

    const temp = new Map({_id: 2, map: map});
    temp.save(function (err) {
        if (err) return handleError(err);
    
    });
    
};

I export the function to my index.js file and run the function there, but I get the error:

const temp= new Map({_id: 2, map: map});
             ^

TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

Can naybody help me with this?

thanks a lot

1 Answers

In the situation where you get the error, you're inadvertently using JavaScript's standard Map constructor, not your own Map constructor. If you pass an argument to JavaScript's Map constructor, that argument must be iterable.

So the fix is to make sure your constructor is the one in scope where you use it.

I strongly recommend not naming things so that they conflict with things in the JavaScript standard library. Perhaps consider calling your constructor XYZMap where XYZ is something that identifies what it means in your schema. Then you won't have the name conflict and you'll get a more obvious error when you don't have it in scope. (The error would be ReferenceError: XYZMap is not defined which hopefully makes it clearer what's happening.)

Related