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

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

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

然而,这似乎是不可能的,因为多维数组不受支持。喝倒采!有人能建议解决这个问题吗?我想要多数组格式的块,这样我就可以使用坐标来访问它们。

最佳答案

一种可能的解决方法是使用Schema.Types.Mixed。假设您需要创建一个2x2数组的block对象(我没有测试此代码):

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

然后,对接下来的两个对象block3block4执行相同的操作。

07-28 02:42
查看更多