Alex Rivera | Logout

Node, Mongoose, problems saving multiple-depths of nested schema

Asked 2011-11-23T13:00:16.137
8

I'm having trouble working out how to insert multiple-depths of nested schema in MongoDB, via Mongoose and node.js.

The example below is a bit contrived but should hopefully explain my problem. As for why each schema is defined as a full model but not used in the example, that's just because in my real-world problem, they are actual, usable models and I wanted this example to be realistic in case it's relevant.

So here are the example schema definitions in reverse order, ie. smallest Russian-doll first:

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

Hopefully you can tell from this that there is a main model, StationeryBox, which has a label and contains two compartments for DrawingTools and MeasuringTools which are nested schema. They in turn have their own labels and contain nested schemas for Pens and Rulers. The problem I'm having is inserted the 2nd level nesting, ie. pens/rulers. So based on the mongoose docs, creating the top level model, and p

Edit
Report

1 Answer

10

You are extremely close, the problem is actually in your Schema definitions. It all comes down to the difference between a Schema object and a Model object. When specifying mongoose Schema with embedded documents, you can only point to other Schema.

var DrawingToolsSchema = new Schema({
  label: String,
  pens: [Pen] // uh-oh, broken! Pen is a Model.
});

However, you do have this correct for your first level of embedded documents defined in StationeryBoxSchema.

var StationeryBoxSchema = new Schema({
  label: String,
  drawingTools: [DrawingToolsSchema], // yes! DrawingToolsSchema is a Schema
  measuringTools: [MeasuringToolsSchema] // this one too.
});

This difference accounts for all of your unexpected behaviour later on.

answered 2011-11-26T08:10:08.910

Your Answer