Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to establish a foreign key relationship in MongoDB?

I have a postgreSQL database that has 3 tables named customer, product and purchase_order. Every table has id_ as the primary key. Table purchase_order also has customer_id (id_ field of customer table) and product_id (id_ field of product table) as foreign keys.

I want to create the same DB on MongoDB. However, I'm not sure how to establish foreign keys. I have researched it and found out that it is pretty much up to me how to do it. So, this is how I did purchase_order table on MongoDB:

{"_id":{"$oid":"5f5639cdb675b2a13db059b3"},
"customer_id":{"$oid":"5f563a08b675b2a13db059b1"},
"product_id":{"$oid":"5f563a13b675b2a13db059b2"},
"status":false}

My goal is to write a spring application to perform CRUD methods. On postgreSQL, I added foreign key constraints on DB and @OneToMany & @ManyToOne annotations on my code to establish foreign keys. However, I'm not sure how to do it for MongoDB. Does my MongoDB document correctly represent the foreign keys? How can I make sure to establish my foreign keys on my spring application for MongoDB?

like image 302
Dilara Daria Avatar asked Oct 28 '25 15:10

Dilara Daria


1 Answers

If you are using JavaScript on your backend, what you are looking for can be easily achieved with Mongoose!

This involves creating a Schema for an entity and specifying a ref property for the entity's foreign key field/column that matches the name of an existing model.

Following this, whenever you query the database for a single document, you can also add or populate the details for the foreign key field.

Kindly view this on getting started with mongoose if you are not using it or familiar with it, and then move on to this documentation which provides examples for populating the foreign key field when you make a query.

In your specific case a given schema could look like this:

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

const CustomerSchema = new Schema({
   _id: {
    type: Schema.Types.ObjectId,
  }
  // Other relevant fields
})

const ProductSchema = new Schema({
   _id: {
    type: Schema.Types.ObjectId,
  }
  // Other relevant fields
})

const ProductOrderSchema = new Schema({
  _id: {
    type: Schema.Types.ObjectId,
  },
  customer_id: {
    type: Schema.Types.ObjectId,
    ref: 'Customer'
  },
  product_id: {
    type: Schema.Types.ObjectId,
    ref: 'Product'
  }
});

// Your models
const Customer = mongoose.model('Customer', CustomerSchema);
const Product = mongoose.model('Product', ProductSchema);
const ProductOrder = mongoose.model('ProductOrder', ProductOrderSchema);


Hope you can get this sorted out relatively easily!

like image 142
rexess Avatar answered Oct 31 '25 05:10

rexess



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!