Dealing with circular dependencies in mongoose: Strategies and solutions

I am working on a code snippet for my application

const citySchema = new Schema({
cityName: {
    type: String,
    required: true,
  },
  citizen:[{
      type: Schema.Types.ObjectId,
      ref: "Citizen",
  }],
});
module.exports = mongoose.model("City", citySchema);


const citizenSchema = new Schema({
  citizenName: {
    type: String,
    required: true,
  },
  city:{
      type: Schema.Types.ObjectId,
      ref: "City",
  },
});

module.exports = mongoose.model("Citizen", citizenSchema);

router.post('/', (req, res) => {
      // req.body.cityName
      // req.body.citizenName
})

When making a POST request, I receive both the city name (for a new city) and citizen name (for a new citizen) that are not already in the database. However, I want to ensure that both these schemas are updated correctly by:

  • Ensuring City contains references to Citizens
  • Ensuring Citizen contains reference to the City

How can I achieve this? Your assistance would be much appreciated.

Answer №1

Instead of following that approach, I highly recommend utilizing referencing through pre-hook middleware in your data model for a more efficient process.

Your code should resemble the following:

const citySchema = new Schema({
cityName: {
    type: String,
    required: true,
  },
  citizen:[{
      type: Schema.Types.ObjectId,
      ref: "Citizen",
  }],
});

// Query middleware to populate the 'citizen' attribute whenever the 'find' function is invoked.
citySchema.pre(/^find/, function (next) {
  this.populate('citizen');
  next();
});

module.exports = mongoose.model("City", citySchema);

const citizenSchema = new Schema({
  citizenName: {
    type: String,
    required: true,
  },
  city:{
      type: Schema.Types.ObjectId,
      ref: "City",
  },
});

citizenSchema.pre(/^find/, function (next) {
  this.populate('city');
  next();
});

module.exports = mongoose.model("Citizen", citizenSchema);

If you wish to only select the ID and not the complete data, an example implementation could be as follows:

citizenSchema.pre(/^find/, function (next) {
  this.populate({
    path: 'city',
    select: '_id',
  });
  next();
});

Explanation:

  • By incorporating this method, every time Mongoose functions like findByIdAndUpdate, find, findOne are executed, the referenced data will be displayed in the city and citizen attributes. This proves to be more efficient rather than updating each time new data is introduced.
  • The populate function serves to populate the attributes with data from another data model.
  • The object within the populate method specifies the model's 'name' (in the path) and determines which data to extract from the referenced model. In this instance, only the _id attribute is selected.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using inline CSS to apply conditional styles to a component in React is a great way to customize the

I'm currently working on customizing the styles of some buttons depending on their 'active' status and whether the user is hovering over them. So far, it's partially working but I'm encountering behavior that I can't fully com ...

The suggestions for Google Places Autocomplete in Angular 2 are failing to display

I'm currently implementing Google Places Autocomplete using the AGM library. Below is the input section in my component HTML for search functionality. <form #addressForm="ngForm" novalidate name="AddressForm"> <div class="form-group"&g ...

Resolving Node.js Absolute Module Paths with TypeScript

Currently, I am facing an issue where the modules need to be resolved based on the baseUrl so that the output code is compatible with node.js. Here is my file path: src/server/index.ts import express = require('express'); import {port, database ...

The ExpressJS router middleware is not capable of rendering views

Need help configuring routes with Express Router middleware. Having trouble rendering templates from the views directory, except for index.jade at path http:localhost:3000/. The router is not sending any response as expected. Here's a section of my co ...

Error in Angular syntax

Just started learning angular and I'm facing some issues with my code. It seems there is a syntax error, but I can't seem to pinpoint it. Any help would be greatly appreciated. Thanks in advance. Here's the error message: Error: [$parse:syn ...

Securing string parameters in Django templates for JavaScript function usage

Can anyone help me with a JavaScript function that is returning a set of objects? return Func("{{id}}", "{{name}}") I'm encountering an issue when passing strings that contain quotes, such as "Dr.Seuss' "ABC""BOOk"", which leads to invalid synt ...

Create a router link in Vue using the command "Vue

I have a Vue application that displays videos. I am looking to automatically generate a random router link every time I click on: <router-link to="/video/this_value_to_be_random">Random video</router-link> Within the component: <vue-vide ...

Tips for concealing content within table cells

I am facing an issue with my form that contains a table. When the user clicks on the radio button labeled "No", I want the content of the subsequent cells in that row to become visible. However, when they click on "Yes", the content should be hidden again. ...

Indicate the Content-Type when sending a 304 Not Modified response

app.use(express.static('./public')); Express utilizes the provided snippet to send a proper mime but only on the first request. Subsequent requests that result in a 304 Not Modified response do not include a Content-Type header. Can Express be ...

ReactJS onClick event not functioning as expected - no action occurs in the browser or in the system console

I've gone through numerous discussions on this issue, but I'm still unable to resolve it. /** @jsx React.DOM */ var React = require('react/addons'); var SegmentComponent = React.createClass({ handleThatEvent: function (e) { ...

Validation of input and authentication in the architecture of microservices and API gateways

Where should the input validation and authentication validation be performed in a microservices architecture? Should it happen in the api-gateway, each individual microservice, or a combination of both? Perhaps some validation should occur in the api-gate ...

Saving user-generated inputs within a React.js component's state, focusing on securely handling passwords

Curious about forms in React.js? I don't have any issues, but I'm wondering if there are potential flaws in my approach. I've set up a basic form with two inputs for email and password: <input type="email" name="email" value= ...

The problem of heavy images not uploading persists when using Ajax/Jquery, as the FormData appears to

I have encountered an issue while running this code for images. It works perfectly for small images up to 2.5mb each, and the form is supposed to handle a maximum of 8 images. However, when I try to upload images larger than 4mb, or more than one such imag ...

The dropdown items in the Tailwind menu fail to pop out from the React Next.js card component

My dropdown menu component, called DropdownWithSearch, is encountering an issue where it opens inside the card component (UserAssignForm) instead of popping out as expected. You can view the problem here. The DropdownWithSearch component import { Menu, Tr ...

Ways to forward a webpage once validation has been completed

I have a login form that is being validated using jQuery/Ajax to receive a JSON response. The form calls a PHP page called add-data.php. Upon successful validation, I want to redirect to another page after displaying the message Successfully logged!: if ...

Ways to access the value of an input field using Javascript

I am currently utilizing the valums-file-uploader plugin for file uploads via ajax. However, I have encountered an issue with its functionality. Below is the script that I am using: <input type="text" id="Gaurav" name="Gaurav" /> <script src="fil ...

How can Vue JS 3 components exchange data between each other?

I am attempting to share data from a variable favorite_count in the Favorites component located in the file Favorites.vue. My goal is to pass this data to the App Component in the App.vue file but I have been unsuccessful so far. I want any changes made to ...

Encountering issues with Jest Setup in Next.js as it appears to unexpectedly include a React import in index.test.js

Hey there, I've been pondering over this issue for the past few days. It appears to be a common error with multiple solutions. I'm facing the dreaded: Jest encountered an unexpected token /__tests__/index.test.js:16 import React from "r ...

struggling to develop a sophisticated 'shopping cart organization' program

I am in the process of creating a database for video spots, where users can view and modify a list of spots. I am currently working on implementing a cart system that automatically stores checked spot IDs as cookies, allowing users to browse multiple pages ...

Unraveling the mystery: Retrieving data from various child components within a Vue parent component

Currently, I am in the process of constructing a view that includes a primary component called ContentComponent. This component acts as a container for a series of sub-components, each representing a form module. The list of forms include: EvaluationForm ...