【发布时间】:2013-05-15 17:55:53
【问题描述】:
我无法确定如何通过 Mongoose 和 node.js 在 MongoDB 中插入多个深度的嵌套模式。
下面的例子有点做作,但希望能解释我的问题。至于为什么每个模式都被定义为一个完整的模型但没有在示例中使用,那只是因为在我的实际问题中,它们是实际的、可用的模型,我希望这个示例是现实的,以防万一它是相关的。
所以这里是相反顺序的示例模式定义,即。最小的俄罗斯娃娃优先:
// Define pen model
var PenSchema = new Schema({
color: String // black, blue or red
});
var Pen = mongoose.model('Pen', PenSchema);
// Define ruler model
var RulerSchema = new Schema({
units: String // inches or millimetres
});
var Ruler = mongoose.model('Ruler', RulerSchema);
// --------
// Define drawing tools model
var DrawingToolsSchema = new Schema({
label: String,
pens: [Pen]
});
var DrawingTools = mongoose.model('DrawingTools', DrawingToolsSchema);
// Define measuring tools model
var MeasuringToolsSchema = new Schema({
label: String,
ruler: [Ruler]
});
var MeasuringTools = mongoose.model('MeasuringTools', MeasuringToolsSchema);
// --------
// Define stationery box model
// It has a label and two compartments - tools for drawing and measuring
var StationeryBoxSchema = new Schema({
label: String,
drawingTools: [DrawingToolsSchema],
measuringTools: [MeasuringToolsSchema]
});
var StationeryBox = mongoose.model('StationeryBox', StationeryBoxSchema);
希望您能从中看出有一个主模型,StationeryBox,它有一个标签并包含两个用于嵌套模式的绘图工具和测量工具的隔间。它们又具有自己的标签并包含钢笔和标尺的嵌套模式。我遇到的问题是插入了第二级嵌套,即。笔/尺子。因此,基于 mongoose 文档,创建顶级模型并推入第一个嵌套对象工作正常,然后麻烦来了。例如:
// To create my stationery box - this works
var stationery = new StationeryBox({ label: 'My Stationery Box' });
// To add the nested compartments - this works
stationery.drawingTools.push({ label: 'My Pens' });
stationery.measuringTools.push({ label: 'My Rulers' });
// But this is wrong as 'stationery.drawingTools.pens' is undefined
stationery.drawingTools.pens.push({ color: 'red' });
stationery.drawingTools.pens.push({ color: 'black' });
如果我后退一步,尝试在插入绘图工具的同时插入笔:
// Also wrong - presumably the second level of nesting is the problem
stationery.drawingTools.push({
label: 'My Pens',
pens: [ // These object represent second levels of nested schema
{ color: 'red' },
{ color: 'black' }
]
});
我知道这不是一个超现实的示例,但它是我正在构建的真实系统的简化示例,这是说明这一点的最简单方法。
实际的保存当然是在这之后发生的,我已经把它省略了,但是我是否需要在保存回调中添加这些下一个级别?
如果有人能告诉我我在这方面哪里出了问题或指出我正确的方向,我会给你买一个漂亮的蛋糕(我害怕只有想象中的蛋糕,除非你住在我附近)。
【问题讨论】:
标签: mongodb node.js nested models mongoose