Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose error: nesting Schemas

I have a question about nesting Mongoose schema.

Here is a simple code snippet

var aSchema = new Schema({bar: String});
var bSchema = new Schema({a: aSchema, foo: String});
var cSchema = new Schema({as: [aSchema], foo:String});

This will throw TypeError on bSchema: TypeError: Undefined type at 's' Did you try nesting Schemas? You can only nest using refs or arrays., but works fine for cSchema.

Just want to ask why bSchema does not work. Cannot find explanation in Mongoose doc. Thanks.

like image 430
NullSpace Avatar asked Dec 02 '14 21:12

NullSpace


1 Answers

MongoDB is not a relational database. This can cause confusion for some who are used to the RDBS model (I still get tripped up occasionally...but I'm really not a DB guy).

Oftentimes, you'll find it beneficial to reference other documents in your Mongo entities. Mongoose schemas provide a very simple and effective way to do this that feels very relational.

When defining a schema that will store a reference to a different type of document, you define the relevant property as an object with a type and a ref. Typically when defining schema properties, you can simply say: a: Number; however, Mongoose provides many different options for a schema property other than type:

a: {
   type: Number,
   required: true   
}

Setting required: true will prevent us from saving a document where the a property is not present.

Once you understand how to define your schemas with object definitions, you can leverage Mongoose's population mechanic:

a: {
   type: Mongoose.Schema.ObjectId,
   ref: 'a'
}

This tells Mongoose to store the ObjectId (a Mongoose-specific identifier) of a specific a document as the a property of our schema. Still following me?

When setting this property on a Mongoose document, you can simply say: doc.a = myA. When you go to save doc, Mongoose will automagically make the conversion and only store the ID in your database.

When retrieving a document that references another schema, you'll need to populate. I won't go into that, but its pretty simple - check out the documentation.

like image 74
Jordan Foreman Avatar answered Oct 03 '22 12:10

Jordan Foreman