multidimensional array的Mongoose模式解决方法

我正在写一个networking应用程序,必须保存网格的数据。 像战舰一样思考。 我想能够做到这一点:

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

但是,这似乎是不可能的,因为不支持multidimensional array。 嘘! 任何人都可以提出一个解决这个问题? 我想多个数组格式的块,所以我可以使用坐标来访问它们。

一个可能的解决方法是使用Schema.Types.Mixed 。 假设你需要创build一个2×2的block对象数组(我没有testing过这个代码):

 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? 

现在假设你在这里创build了4个block对象(block1,block2,block3,block4),那么你可以这样做:

 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做同样的block4