I am aware of how to set up a one to many relationship between Mongoose entities, with the following type of code :
friends: [{type: ObjectId, ref: 'User'}]
But what if I want to only have a one-to-one relationship - Such as which client this user is related to?
First of all, there is a huge difference between relationships in MongoDB and those in SQL based datastores (you need to be clear about this from the get-go).
Relationships in MongoDB are just representations of related data. There is no mechanism which maintains the integrity of these relationships.
What mongoose does with refs is just use the field having the ref
option to query the _id
field of documents in the referenced collection. This is used for operations like populate
(which internally calls findById
queries on the target collection and replaces the referenced field with the documents).
This being cleared, you can store one or many IDs for the referenced collection in the field, thus creating one-to-one or one-to-many "relationships".
So, to store a single ID for a referenced collection, the syntax would be:
client: {type: Mongoose.Schema.Types.ObjectId, ref: 'Client'} //No arrays, as we want to store a single ID only.
In the same way, you can store many IDs for the referenced collection like so:
friends: [{type: Mongoose.Schema.Types.ObjectId, ref: 'User'}] //The array stores multiple IDs, creating a one-to-many "relationship"
EDIT:
Make sure you have required
the Mongoose module at the beginning.
var Mongoose = require('mongoose');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With