Individual relationship with mongooses?

I know how to set up a one-to-many relationship between Mongoose objects with the following code type:

friends: [{type: ObjectId, ref: 'User'}] 

But what if I want to have only a one-to-one relationship — for example, to which client does this user belong?

+5
source share
1 answer

First of all, there is a huge difference between relationships in MongoDB and data in SQL-based data stores (you need to clearly understand this with get-go).

Relations in MongoDB are just representations of related data. There is no mechanism that supports the integrity of these relations.

What mongoose does with refs, it simply uses a field that has a ref parameter to query the _id document _id in the reference collection. This is used for operations of type populate (which internally calls findById queries in the target collection and replaces the reference field with documents).

This is cleared, you can save one or more identifiers for the reference collection in the field, thereby creating a one-to-one or one-to-many relationship.

So, to save one identifier for the reference collection, the syntax will look like this:

 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 identifiers for a reference collection like this:

 friends: [{type: Mongoose.Schema.Types.ObjectId, ref: 'User'}] //The array stores multiple IDs, creating a one-to-many "relationship" 

EDIT:

Make sure you have the require d Mongoose module at the beginning.

 var Mongoose = require('mongoose'); 
+5
source

All Articles