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.
a
property ofbSchema
supposed to be a reference to anaSchema
object? Don't do that. Do:a:{type: Mongoose.Schema.ObjectId', ref: 'a'}
where thea
inref:a
is the name of the mongoose model that you create usingaSchema