One-To-One relationship with mongoose?
Asked Answered
C

4

14

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?

Crewelwork answered 16/8, 2015 at 18:59 Comment(2)
Then simply don't use an array.Shrine
Thanks, but this doesn't really help - I am new to using node and mongoose, so the syntax is alien to me.Crewelwork
U
27

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');
Ungava answered 17/8, 2015 at 6:59 Comment(5)
When I do that though, I get the following error : "Reference Error : ObjectId is not defined"Crewelwork
Have you installed the Mongoose module using npm install ?Ungava
Yes. I have it all working for all kinds of interactions with my mongo database. But when I try to do that syntax, it doesn't like it. It works with the array (like the friends example you showed) but without the array it complains.Crewelwork
I literally just copy and pasted it - but changed 'Client' to 'Company' - because that is the name of my model - but it really doesn't like the ObjectId - and I do have both lines from the edit in there.Crewelwork
Which version of Mongoose are you using? In older versions, ObjectId can be accessed using only Mongoose.Schema.ObjectIdUngava
B
1

For one to one relationships, use embedded data model, so your application can retrieve the complete information retrieval with one query. For more info visit https://docs.mongodb.com/manual/tutorial/model-embedded-one-to-one-relationships-between-documents/

Boomer answered 2/3, 2019 at 5:45 Comment(0)
S
0

The answer @ZeMoon explained above is technically somewhat acceptable, but it cannot be implemented in actual program, as when tried to sync data into db, you need to submit 2 tables in parallel, and I mean in parallel like real synchronous.

This guy gave excellent explanation on why it is currently impossible to link 1 to 1 relation tables. Erik Phillips1:1 relation in sql

when you use await Promise.all([]), it still loads tables in sequence, and there is currently no way to implement this kind of relation straightaway.

What you can do is create another table, and link their PK.

Sauveur answered 7/11, 2023 at 17:22 Comment(0)
S
0

Setting up one-to-one relationship is similar to one-to-many relationship but you should not include the array. You directly reference the related entity using a single field.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// User schema
const userSchema = new Schema({
    username: String,
    email: String,
    // Reference to the Profile schema
    profile: { type: Schema.Types.ObjectId, ref: 'Profile' }
});

// Profile Schema
const profileSchema = new Schema({
    firstName: String,
    lastName: String,
    // Reference to the User schema
    user: { type: Schema.Types.ObjectId, ref: 'User' }
});
Saddleback answered 24/3 at 17:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.