What is the best way to add a new project and make updates to an existing project within an array?

Looking to add a new project and update existing projects within an array.

Here's my plan in pseudo-JSON format.

How can I update Project A in MongoDB?

{
  _id : ...,
  userName: milad ,
  projets : [
    { .. projectId, pName, location .... A },
    { .. projectId, pName, location .... B },
    { .. projectId, pName, location .... C },
  ]
}

What is the process for inserting Project D in MongoDB?

 {
      _id : ...,
      userName: milad ,
      projets : [
        { .. projectId, pName, location .... A },
        { .. projectId, pName, location .... B },
        { .. projectId, pName, location .... C },
        { .. projectId, pName, location .... D },
      ]
    }

Answer №1

When performing an update with findOneAndUpdate(), remember to utilize the $push operation for inserting new documents.

db1.findOneAndUpdate({ _id: 1 }, { $push: { projects: {name:"new project" }} });

If you need to update a specific element within an array, use the following syntax:

db1.findOneAndUpdate({ id: 1, "projects.projectid": 2 }, { $set: { "projects.$.name": "updated name" } }); 

Answer №2


const addNewProject = async (newProj, _id) {
  
  let existingProjObj = await Project.findOne({_id});

  let updatedProjArr = [...existingProjObj.projects, newProj];

  let updatedProj = await Project.findOneAndUpdate({_id,{projects:updatedProjArr});
}

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

Can you demonstrate how to incorporate a new line within a for loop?

I have an array of letters and I need to display them on the screen using a for loop. My goal is to make every sixth letter appear on a new line. Here is the code snippet: https://i.stack.imgur.com/lHFqq.jpg <script> export default { data() { ...

We will explore the process of accessing a CSS file within an Angular

I'm having trouble reading a CSS file from my UI project directory in AngularJS. When I make a GET call, I only get the index.html file as output instead of the CSS file. Can anyone provide some guidance on how to properly access the CSS file? Any su ...

What could be preventing the background image from displaying properly?

I had the idea to create a game where players have to flip cards to reveal what's on the back, but I'm struggling to get the background image to display properly. As a newcomer to Vue, I'm not sure if I made a mistake somewhere. My intuition ...

Filtering data from an Ajax request in Angular using a filter function with JSON

Hi everyone, I recently started learning AngularJS and created a basic item list with search functionality and pagination. Everything was working smoothly, so I decided to move my list outside the controller and store it as a JSON file. Here's what ...

Exploring Methods to Iterate through an Object Utilizing Two Arrays

Attempting to iterate through states passed as props in another component state = { question:[firstQ, secondQ, thirdQ], tag:[[1,2,3],[4,6],[a,b,c,d]] } I aim to display it on the next Componet with a pattern like: FirstQ [tag1] SecondQ ...

Updating a property in an object within an Angular service and accessing it in a different controller

I am currently utilizing a service to transfer variables between two controllers. However, I am encountering difficulties in modifying the value of an object property. My goal is to update this value in the first controller and then access the new value in ...

modify the color of a box within a grid upon clicking it

I am curious if it is possible to change the color of a box when it is clicked. I am working on coding a "calculator layout" and would like to start with this part 1 2 3 4 5 6 7 8 9 0 This is what I have been working on and struggling with. $(docume ...

Locate records that meet criteria in various fields within a nested array in MongoDB

Suppose I have an array of objects (let's call it array A) and I am looking for a way to query MongoDB to find documents where one field matches a property in object 1 from array A, and another field matches a different property in the same object. N ...

Storing blank information into a Mongodb database with Node.js and HTML

Can someone please assist me with solving this problem? const express=require("express"); const app=express(); const bodyparser=require("body-parser"); const cors=require("cors"); const mongoose=require("mongoose"); ...

Storing the path of a nested JSON object in a variable using recursion

Can the "path" of a JSON object be saved to a variable? For example, if we have the following: var obj = {"Mattress": { "productDelivered": "Arranged by Retailer", "productAge": { "ye ...

Is it possible to create an API directly within the URL of a React.js application, similar to how Next.js allows?

When using Next.js, I can access my application on localhost:3000, and also access my API from localhost:3000/api/hello. I'm curious if there is a way to achieve this same setup with React.js and another framework like Express.js? If Next.js is not ...

I'm having trouble locating the 'mongodb' module on Heroku

Having an issue with my Express app on Heroku. It was working fine locally but now I'm getting this 'Cannot find module 'mongodb'' error upon deployment: Cannot find module 'mongodb' The strange thing is that nothin ...

Having trouble with my JavaScript code in Visual Studio because of a bundler issue. It's throwing an Uncaught ReferenceError for trying to access a variable before initialization

My AJAX request looks like this: $.ajax({ method: 'GET', url: '/api/some-data', headers: { 'Content-Type': 'application/json' }, success: function(data) { if (data != null) { var userDat ...

If you want to retrieve the calculated value of a div using jQuery

I have a scenario where I have 3 list items (li) under an unordered list (ul). I am interested in finding the height of these list items, but without explicitly defining their height. So far, when inspecting with Firebug, I noticed that the computed height ...

Refresh the page to change the section using vue.js

I am currently working on a website using Laravel and Vue.js. I require two separate sections for the site: Site: https://www.example.com Admin: https://www.example.com/admin Within the resource/js/app.js file, I have included the main components as fo ...

Update the Vue method

Is there a way to optimize the following method or provide any suggestions on what can be improved? I am trying to create a function that converts author names from uppercase to only the first letter capitalized, while excluding certain words ('de&apo ...

Attempting to incorporate country flags into the Currency Converter feature

www.womenpalace.com hello :) i'm looking to customize my Currency Converter with Flags images. this is the code for the converter: <select id ="currencies" class="currencies" name="currencies" data-default-shop-currency="{{ shop.currency }}" ...

How to Utilize Vue and Checkboxes for Filtering a List?

My current challenge involves filtering a list of posts based on userId using checkboxes. The data is being retrieved from: https://jsonplaceholder.typicode.com/posts. I aim to include checkboxes that, when selected, will filter the list by userId. Here is ...

Creating code that is easily testable for a unique test scenario

My function, readFile(path, callback), is asynchronous. The first time it reads a file, it retrieves the content from the file system and saves it in memory. For subsequent reads of the same file, the function simply returns the cached content from memor ...

How can AngularJS handle multiple views sharing the same controller and ensure that the controller is executed only once?

Currently, I am facing a situation where I have two separate views that I would like to control within a single controller. The issue is, the controller is being executed twice. Is there a way to link multiple views to the same controller without the cont ...