Question

I'm writing a web app that has to save data for a grid. Think like battleships. I want to be able to do this:

var block = mongoose.Schema({
  type: Number,
  colour: String
});

var schema = mongoose.Schema({
  grid: [[block]]
});

However it seems this is not possible as multidimensional arrays aren't supported. Boo! Can anyone suggest a work around for this? I want the blocks in multi array format so I can use coordinates to access them.

Was it helpful?

Solution

A possible workaround is to use Schema.Types.Mixed. Let's say you need to create a 2x2 array of block objects (I haven't tested this code):

var mongoose = require('mongoose')
    , Schema = mongoose.Schema,
    , Mixed = Schema.Types.Mixed;

var block = new Schema({
  type: Number,
  colour: String
});

var gridSchema = new Schema({ 
    arr: { type: Mixed, default: [] }
});

var YourGrid = db.model('YourGrid', gridSchema); // battleship is 2D, right?

Now, let's assume that you create here 4 'block' objects (block1, block2, block3, block4), then you could do:

var yourGrid = new YourGrid;

yourGrid.arr.push([block1, block2]);
// now you have to tell mongoose that the value has changed
    // because with Mixed types it's not done automatically...
    yourGrid.markModified('arr');
yourGrid.save();

Then, do the same for the next 2 objects, block3 and block4.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top