issues with updating a MongoDB collection

One challenge I'm facing with my social media app is that I have two separate collections - one for users and the other for user posts. When I update information in a user's collection, it should also reflect in the corresponding posts (as the post collection contains user data), but currently, this only applies to new posts created after the update, not older ones. How can I resolve this issue?

USER SCHEMA

const userSchema = new Schema({
    name: { type: String, required: true },
    lastname: { type: String, required: true },
    username: { type: String, required: true },
    email: { type: String, required: true },
    password: { type: String, required: true, minlength: 8 },
    avatar: { data: Buffer, contentType: String },
});

POST SCHEMA

const postSchema = new Schema({
   user: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
   name: { type: String, required: true },
   lastname: { type: String },
   username: { type: String },
   avatar: { data: Buffer, contentType: String },
   date: { type: Date, default: Date.now() },
   textOfThePost: { type: String, required: true },
});

EDIT FUNCTION EXPRESS/MONGOOSE

router.put("/edit_profile", async (req, res) => {
  try {
    const { name, lastname, username } = req.body;
    const user = await User.findById(req.user).select("-password");

     if (!user) return res.status(404).json("User doesn't exists");

     if (name) user.name = name;
     if (lastname) user.lastname = lastname;
     if (username) user.username = username;

     await user.save();
     res.json(user);
  } catch (err) {
     res.status(500).json({ error: err.message });
 }
 };

Answer №1

If you want to optimize your data storage, consider using the updateMany() method.

const result = await Post.updateMany({ user: user.id }, { name: user.name, username: user.username /* ... */ });

Instead of duplicating user information in both the post and user models, you can utilize the populate() method similar to SQL joins. This way, you can avoid storing redundant data on your post model and automatically fetch the relevant user model when querying posts based on user id.

myPost.populate('user')

Keep in mind that specifying the ref is essential for mongoose to properly populate the user field.

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

The act of transferring non-textual information into web-based applications

Is it possible for a user to copy and paste a selection of pixels from MSPaint into a browser-based app using JavaScript in current browsers? If not, will HTML5 make this possible in the future? Alternatively, could something like Flex or Silverlight be us ...

"Enhance user experience with the React Popover feature from Material UI

Looking for help on creating a dynamic color palette with a hover feature for the PaletteIcon. The issue I'm facing is that when I try to select a color, the palette disappears. Is there a specific property I should add to the React component or anoth ...

Unit testing component in Ionic 2 with Ionic's specific markup and elements

Within my Angular 2 component for an Ionic 2 app, I utilize Ionic's markup as shown below: <ion-card> <h3>{{ rawcontent.name }}</h3> <p *ngIf="rawcontent.description">{{ rawcontent.description }}</p> </ion-car ...

Maximizing the Potential of SSJS ContinueRequest

Is there a way to incorporate ContinueRequest into the script shown below in order to bypass the 2500 limit? <script runat="server"> Platform.Load("Core","1"); try { var DEkey = Request.GetQueryStringParameter(&qu ...

Setting up Spectron

I attempted to install Spectron using the following command: npm install --save-dev spectron However, I encountered the following error message: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\P ...

The UseEffect function works flawlessly on the initial attempt, however, it encounters issues after being refreshed

Upon refreshing the code once, it operates flawlessly. However, when refreshed twice, it reverts the money and luck values back to 1 and 10, the default settings. Is there a solution to this issue? The initial useEffect function is responsible for fetching ...

"Learn how to seamlessly submit a form without reloading the page and send data back to the same page using Node and Express

I've already reviewed a few questions on this platform. They all focus on submitting post requests, but I believe the process should be similar for get requests as well. Therefore, I made modifications to my code to accommodate get requests. However, ...

Is there a way to determine if a webpage is being accessed from a website or from a local file system?

While this question has been raised in the past, none of the answers provided seem to be accurate. Unfortunately, I am unable to comment on the original question or answers. Thus, following suggestions given to me, I have decided to create a new question. ...

Retrieve the top 5 data fields from a leaderboard in MongoDB

I am currently working with a simple table that displays data in the following format: { _id: 55dbdffeaba8ee274d3b9f89, firstname: 'Jim', lastname: 'Kirk', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

Divs in jQuery smoothly slide down when a category is chosen

As I work on a large website, I have hidden div tags in my HTML that I want to be displayed when a user selects a specific category. However, due to the size of the site, there are many hidden divs that need to be revealed based on different categories sel ...

Refreshing a Node.js server page upon receiving a JSON update

My web application serves as a monitoring interface for tracking changes in "objects" processed by the computer, specifically when they exceed a certain threshold. The Node Js server is running on the same machine and is responsible for displaying data in ...

How can we eliminate the need for specifying the order of generic arguments in TypeScript?

In the development of my middleware engine, I have incorporated various generic arguments that are specific to the particular implementation in use. export type Middleware< Store = never, Args = unknown, Response = unknown > = ( context: { ...

Having trouble processing the Firebase snapshot with Node.js

I have a question regarding a snapshot; ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {}) After printing the snapshot with ; console.log(snapshot.val()); This is the output that gets printed; {'-LBHEpgffPTQnxWIT ...

Passing inline CSS styles from parent component to child component in Vue

I am currently using vue.js with vuetify, and I need to position a button on top of a canvas component (managed by the Konva library). I successfully achieved this by using absolute positioning for the button. However, in order to organize my code better, ...

Retrieving particular excerpts from a block of text that includes the keyword "javascript."

I have a chunk of string containing HTML source code. Currently, I am trying to read specific tags that I need using JavaScript. Since I am new to programming, I'm unsure how to proceed. Can anyone assist me with this? The issue lies in the following ...

"Subtle Website Background Fade Effect When Menu is Hovered Over

Click on the following link to observe a transition effect that occurs on the body of the website when interacting with the main menu system: Here is the website Do you know what this effect is called and how it can be integrated into a website? ...

In search of javascript implementations of the pubhubsubbub protocol that are open source

Can you list out some of the open-source Javascript implementations for the PubSubHubbub protocol, starting with the publishing side? ...

There are multiple sets of radio buttons within nested ng-repeats, but only the final group displays the selected value

I am having an issue with updating a form that contains multiple radio buttons based on data retrieved from an API. The challenge is that only the last set of radio buttons displays the value correctly. Below is the code snippet I am using (angular bracket ...

Using React refs to target multiple elements dynamically with the help of the map

My code effectively catches when the dropdown is clicked outside, and it's working well: displayOptions() { return _.map(this.props.selections, (option, index) => { return ( <div className="ui icon top dropdown" ...

"Encountering an issue with AJAX file upload displaying an error message for

Before I showcase my code, allow me to explain my objective. My goal is to create a page that updates a user's details in the database using AJAX. Initially, I successfully achieved this task. Subsequently, I wanted to enhance the functionality by inc ...