Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-To-One relationship with mongoose?

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?

like image 920
Slippy Avatar asked Aug 16 '15 18:08

Slippy


1 Answers

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');
like image 120
ZeMoon Avatar answered Oct 12 '22 11:10

ZeMoon