如何创建“对象数组的数组"Mongoose.js 中的架构 [英] How to create "array of arrays of objects" schema in Mongoose.js
本文介绍了如何创建“对象数组的数组"Mongoose.js 中的架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要为以下数据结构创建架构:
<代码>{...矩阵: [[{type: "A", count: 6}, {type: "B", count: 4}],[{type: "B", count: 1}, {type: "A", count: 2}, {type: "A", count: 1}],[{type: "C", count: 7}, {type: "A", count: 1}],]}
我在定义架构时尝试这样做,但导致验证错误:
const cellSchema = new mongoose.Schema({类型:字符串,计数:数量});const matrixSchema = new mongoose.Schema({...矩阵:[[cellSchema]]});
现在 Mongoose 似乎支持这种模式语法(
I need to create schema for following data structure:
{
...
matrix: [
[{type: "A", count: 6}, {type: "B", count: 4}],
[{type: "B", count: 1}, {type: "A", count: 2}, {type: "A", count: 1}],
[{type: "C", count: 7}, {type: "A", count: 1}],
]
}
I tried to do so like this while defining my schema, but it caused validation errors:
const cellSchema = new mongoose.Schema({
type: String,
count: Number
});
const matrixSchema = new mongoose.Schema({
...
matrix: [[cellSchema]]
});
it seems that such a schema syntax is supported now in Mongoose (https://github.com/Automattic/mongoose/issues/1361).
解决方案
Sample code to create Array of arrays of object:
const cellSchema = new mongoose.Schema({
type: String,
count: Number
});
const matrixSchema = new mongoose.Schema({
matrix: [[cellSchema]]
});
const Matrix = mongoose.model('Matrix', matrixSchema);
const newMatrix = new Matrix({
matrix: [
[{ type: 'xyz', count: 10 }, { type: 'ABC', count: 20 }],
[{ type: 'pqr', count: 10 }]]
});
newMatrix.save();
这篇关于如何创建“对象数组的数组"Mongoose.js 中的架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文