2014-05-05 27 views
2

我正在編寫一個必須保存網格數據的Web應用程序。像戰艦一樣思考。我想能夠這樣做:用於多維數組的Mongoose模式解決方法

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

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

但是,似乎這是不可能的,因爲多維數組不支持。噓!任何人都可以爲此提出解決方法嗎?我想要多個數組格式的塊,以便我可以使用座標來訪問它們。

回答

1

可能的解決方法是使用Schema.Types.Mixed。比方說,你需要創建block對象的2x2的陣列(我沒有測試此代碼):

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? 

現在,讓我們假設你在這裏創建4個「塊」的對象(塊1,塊2,塊3,塊4 ),那麼你可以做:

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(); 

然後,在接下來的一個2點的對象,block3block4相同。