A guide on looping through an array of objects to add information to a nested array in MongoDB

Currently, I am in the process of developing a blog application and working on an online editor feature. The schema I'm using for this project is outlined below:

 var blogSchema = restful.model('blog-schema', mongoose.Schema({
   title: String,
   preview: String,
   content: [{tag: String, body: String}],
   comments: [{ body: String, date: Date}],
   createdAt: {type: Date, default: Date.now}
 }

For the client-side implementation, I am utilizing react to POST data in the following format:

 [{"type":"h2","body":"azeaeazeae"},{"type":"p","body":"azeaeazeae"}]

In my server side code with express(), I have the following logic:

 blogSchema.update(
  {title: "please work AGAIN"},
  {
     $pushAll: {
      content: test
     }
 },
 function(err, stat, docs) {
  console.log(stat);
 }
)

After checking the stored data with POSTMAN, I noticed that the output was as follows:

"content": [    
{
  "tag": "[object Object],[object Object]",
  "_id": "57b2eced869e03821d446c38"
}

The challenge I am facing now is how to iterate through this array of objects on the server side and correctly push each item to its designated place within the tag and body fields.

Answer №1

After some searching, I finally found the solution:

Below is the code snippet that worked for me:

app.post('/admin', function(req, res) {
   var test = req.body;

   test.map(function(test, i) {
   blogSchema.update(
   {title: "please work AGAIN"},
    {
      $push: {
        content: {
          test: test.type,
          body: test.body
        }
      }
    },
    function(err,stat,dude){
      console.log(stat);
    })
})  

I was able to successfully map the request body and use the $push method in MongoDB. Apologies for posting the question earlier, but I'm thrilled to have figured it out!

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

Retrieve all the keys from an array of objects that contain values in the form of arrays

Looking for an efficient way to extract all keys from an array of objects whose values are arrays, without any duplicates. I want to achieve this using pure JavaScript, without relying on libraries like lodash or underscore. Any suggestions on how to impro ...

Create a JavaScript variable every few seconds and generate a JSON array of the variable whenever it is updated

My variable, which consists of random numbers generated by mathrandom every second, such as "14323121", needs to be saved to an array for the latest 10 updates. function EveryOneSec() { var numbers = Math.random(); // I want to create an array from th ...

An issue has been identified in the bubble sort algorithm causing certain numerical lists to not be properly sorted when implemented in NodeJS

I am just beginning to learn about algorithms and have started with the bubble sort. I wrote my own implementation and it seems to work well most of the time when sorting a list of numbers from 1 to 100. However, occasionally there is one random number th ...

NuxtJS (Vue) loop displaying inaccurate information

I have a dataset that includes multiple languages and their corresponding pages. export const myData = [ { id: 1, lang: "it", items: [ { id: 1, title: "IT Page1", }, { ...

Why is my MongoDB .aggregate not recognizing the $or operator?

Whenever a user sends or receives a message, they should have the ability to archive the message for themselves. Unfortunately, this .aggregate $or function only retrieves documents where the user is the recipient ('to') and has marked 'arc ...

Using a Component's Variable in Another Component in React Native

Hello there! Thank you so much for offering your help. I have a component called PlayerWidget and would like to utilize its state variable isPlaying value in the AlbumHeader Component. Here is the code for the PlayerWidget: import React, { useContext, use ...

Running React Boilerplate with forever is a great way to ensure your application stays

I plan on keeping the react-boilerplate application running indefinitely on the server. I recently came across forever, but I'm uncertain about how to pass parameters to it. The command to start the server looks like this: PORT=80 npm run start:produ ...

Transforming an array of HashMaps into a JSON object within a servlet and showcasing it on a JSP page

Looking to extract all table rows and store them in an array of hashmaps, then convert them into a JSON object to be sent to a JSP page using Ajax and jQuery. Struggling with displaying the content on the JSP page. I've written the code below but need ...

Stop the form submission until validation is complete

I'm currently working on a form and encountering some validation issues. HTML: <form id="regForm" class="form-group" method="POST" action="signup.php"> <div class="col-md-12"> <h2>Job Pocket</h2> </div> <di ...

Mastering the art of integrating Poet with Node.js, Express, and EJS for seamless web development

Recently, I stumbled upon the innovative Poet blog engine and I am intrigued to learn how to integrate it with the EJS template engine. Despite going through the documentation, I'm still puzzled about the process of creating a new post, the required ...

Enhancing search results with data retrieved from a jSON response

At the moment, I am using a logic to generate a list of titles. Now, I would like to include data from the response along with the code for each title in the list. const title = responseData.map(item => { return { label: item.title, val ...

The error "500 window is not defined in Nuxt3 when using the composition API"

Is it possible to detect the user's preference for color scheme and set a data-mode attribute on the document root (html)? I've been struggling with this. In my app.vue code, I have the following: <template> <div> <NuxtLayout /> ...

Running a Single Page Application (SPA) with NGINX: Easy Steps to Setting up Multiple Proxied Locations in NGINX

After successfully deploying my MERN stack website on an Ubuntu 20.x server using pm2 and nginx, I encountered a problem with URL links. Manually entered links or those redirected from my Express routes were not working due to the setup of my nginx configu ...

Adding a characteristic to every item in an array of objects

Currently, I am utilizing Node.js along with Mongoose to interact with a MongoDB database and retrieve an array of objects from a specific collection. However, my aim is to add an additional property to each of these retrieved objects. Below, you can see t ...

Guide on how to retrieve a list of objects from a controller and showcase them utilizing JQuery in a Spring MVC application with ajax functionality

Here is the controller code snippet: @Controller public class MainController { @Autowired SqlSession sqlSession; @Autowired Message messageVO; @RequestMapping(value="getMessages", method=RequestMethod.GET) public @ResponseBody List<Messag ...

Subpar resolution of PNG images displayed in HTML canvas

My attempt to draw a PNG image onto the canvas is resulting in poor quality. I am using the drawImage method as shown below: src = folder+self.cur+".png"; imageObj.src = src; imageObj.onload = function() { context.clearRect(0, 0, cv, ch), context.drawImag ...

Avoiding errors caused by higher order array methods

Is there a way to avoid errors when filtering data? The function below may encounter issues at conversationMember.Name.toLowerCase() if conversationMember is not present. This function is part of a computed property in a Vue application. Feel free to ask ...

The search text box is mysteriously absent from each column in the datatables

I am utilizing jQuery Datatables to construct a table with data retrieved from MySQL. This is how my table appears: LOT_LOCATION, Zone Attribute, LOTID, Design_ID, Board_ID1, QA_WORK_REQUEST_NO, QA_CONTACT_NAME, QA_PROCESS_NAME, CURRENT_QTY, Date, Temp ...

Using NodeJS to trigger a function based on when the UTC server time matches the time entry stored in a Firebase database

Is there a way to activate a function in response to the server's UTC time matching the alertTime recorded in the Firebase database? This feature needs to be able to monitor both past and new entries, ensuring that the function is only triggered when ...

What is the best way to retrieve a document element in React when utilizing an external script?

In my React project, I have successfully implemented a chat button using an external script. However, I encountered an issue where I needed to hide the chat button on specific pages. Since I couldn't access the button's element using a ref, I res ...