Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create one-to-one relation in mongoDb

I read the official documentation but still don't get it https://docs.mongodb.com/manual/tutorial/model-embedded-one-to-one-relationships-between-documents/ Explain me pls, how to create in my example. I have nest.js app with mongoose. Two schemas (2 tables in db):

1)

export type UserModelDocument = UserModel & Document;

@Schema()
export class UserModel {
  @Prop()
  email: string;

  @Prop({ type: MongooseSchema.Types.ObjectId, ref: 'InviteModel' })
  invite: InviteModel;
}

export const UserSchema = SchemaFactory.createForClass(UserModel);
@Schema()
export class InviteModel {

  @Prop()
  status: string;
}

export const InviteSchema = SchemaFactory.createForClass(InviteModel);

And here, in my service i create a user:

async create(createUserDto: CreateUserDto) {
    const userExists = await this.userModel.findOne({ email: createUserDto.email });
    if (userExists) {
      this.logger.error('User already exists');
      throw new NotAcceptableException('User already exists');
    }
    const createdUser = await new this.userModel(createUserDto).save();
//need some operations to save default invite too in the same user
    return toCreateUserDto(createdUser);
  }

How to add a relation one-to-one when registering for a new user, so that the object of the created user is also added invite object. Example:

{userEmail: "[email protected]",
 invite: {
  status: 'not_sent',
 }
}

Сan i do it in one request? or I need to save in different requests?

const createdUser = await new this.userModel(createUserDto).save();
const createdInvite = await new this.inviteModel(createInviteDto).save(); ?
like image 576
Romik romikromik Avatar asked Nov 22 '21 12:11

Romik romikromik


People also ask

Can we create relations in MongoDB?

In MongoDB, a relationship represents how different types of documents are logically related to each other. Relationships like one-to-one, one-to-many, etc., can be represented by using two different models: Embedded document model.

How do you create a relationship between two tables in MongoDB?

To create a relationship in MongoDB, either embed a BSON document within another, or reference it from another. MongoDB databases work differently to relational databases. This is also true of relationships.

How do I create a many to many relationship in MongoDB?

A Many-to-Many relationship (N:M) As there is no single command to implement a many-to-many relationship in a relational database, it is more difficult than a one-to-many relationship. The same is true when using mongoDB to implement them. In fact, you can't use a command to create any type of relationship in MongoDB.

How do I join two documents in MongoDB?

We can join documents on collections in MongoDB by using the $lookup (Aggregation) function. $lookup(Aggregation) creates an outer left join with another collection and helps to filter data from merged data.

How do I create a relationship in MongoDB?

In MongoDB, you can create a relationship using one of the following two methods: Embedded documents. Referenced documents. The method you use will depend on the data, and how you intend to query that data. With MongoDB, you can embed documents within documents. Therefore, a single document can contain its own relationships.

What are the advantages of embedded relationships in MongoDB?

When the relationship is embedded within the document, queries will run faster than if they were spread out over multiple documents. MongoDB only needs to return the one document, rather than joining multiple documents in order to retrieve the relationships. This can provide a major performance boost — especially when working with lots of data.

What happens when multiple users access the same MongoDB document?

When multiple users are accessing the data, there's always a chance that two or more users will try to update the same document with different data. In this case, MongoDB will ensure that no conflict occurs and only one set of data is updated at a time. MongoDB cannot ensure this across multiple documents.

How to perform a one-to-many relationship with embedded documents?

We can also perform a one-to-many relationship using the document reference model. In this model, we maintain the documents separately but one document contains the reference of the other documents. Now we will discuss the one-to-many relationship with embedded documents with the help of an example.


Video Answer


1 Answers

It is well explained in the documentation , if you have less frequently searched data you can offload it to second collection to reduce the size of the main document and improve read performance , in case you need the less frequent data you will make a second request to the second collection. In general if your document in first collection is not so big and no impact on read performance best is to embed the field in the first collection and avoid too much collections and fetch everything in single call.

  1. One-to-one example:

collection 1:

 { _id:"useremail" , frequentData: "the data1"  }

collection 2:

 { _id:"useremail" , lessFrequentData:"the data2"  }
  1. Embedding option:

collection 1:

 { _id:"usermail" , frequentData: "the Data1" , lessFrequentData:"the Data2" }

P.S. my personal observation: mongoDB wiredTiger storage engine is splitting and storing data to 32KB blocks on storage so documents below that size are considered relatively small and embedding seems to be the best option if there is no other specific requirements ... Document size is important , but in the document model design the prefered is the denormalized data , correct indexes creation and utilisation will help more with the performance improvement.

like image 89
R2D2 Avatar answered Oct 28 '22 19:10

R2D2