Reputation: 3209
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.
Upvotes: 2
Views: 2958
Reputation: 7862
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
.
Upvotes: 1