Array of mongoose objects

Struggling to store an array of objects in mongodb using mongoose and node, I am facing challenges with simple validation.

I have defined a Schema and a custom validation function as follows:

const mongoose = require("mongoose");
const fieldsSchema = mongoose.Schema({
  title: {
    type: String,
    minlength: 2,
    maxlength: 250,
  },
  list: {
    type: Array,
    primaryText: {
      type: String,
      minlength: 1,
      maxlength: 250,
    },
    secondaryText: {
      type: String,
      minlength: 2,
      maxlength: 250,
    },
    listType: {
      type: String,
      enum: ["listOne", "listTwo"],
      minlength: 2,
      maxlength: 250,
    },
    items: {
      required: isListTypeTwo,
      type: Array,
      itemTitle: {
        type: String,
        minlength: 2,
        maxlength: 250,
      },
      itemContent: {
        type: String,
        minlength: 2,
        maxlength: 250,
      },
    },
...
...
  1. How can I pass a properly defined structure of an array to my route?

  2. Why is my validation not working?

  3. Should I pass the JSON data in a different manner or structure?

Answer №1

Before you do anything else, make sure to include the body-parser middleware for proper JSON parsing.

const express = require("express");
const bodyParser = require("body-parser");
const app = express(); // no need to call Router()

// parse application/json
app.use(bodyParser.json())

app.post("/", async (req, res) => {
  // your logic here...
});

Is there a way to pass a well-defined array structure to my route without manually accessing each object? For example, instead of: list: req.body.list, something more detailed?

If I understand correctly, using a loop might be the solution to save your fields efficiently.

  const promises = req.body.list.map(async (item) => { // map loop creating an array of promises
    const field = new Field({
      title: req.body.title,
      item,
    });
    return field.save(); // returning the promise
  });

  res.send(Promise.all(promises));

Don't forget to implement a try/catch block to handle and log any potential errors with your mongoose schema:

try {
  const field = new Field({
    title: req.body.title,
    item,
  });
  field.save();
  // success
} catch (error) {
  console.error(error);
}

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

Building a Multifaceted Website using React and Node.js

I've encountered a rather straightforward issue. My goal is to incorporate a second checkout page into my React and Node Website. I initially believed that the solution would be as simple as adding another 'checkout' Route to the Browser Ro ...

The POST request in Node.js encountered an error due to attempting to set headers after they were already sent to the client, resulting in the following message

After creating REST services using Node JS, Express, and Mongo DB, I encountered a problem with my POST request to add users into the database. When testing the service locally using POSTMAN, the user gets added successfully, but the node app crashes (serv ...

Is the examples folder missing from the repository after installing react-router using npm?

After executing the npm install react-router command, it installs version react-router v1.0.3 which includes an examples directory. However, when running the commands: cd node_modules/react-router ls The resulting output is: CHANGES.md README.m ...

Interrogate Firebase to retrieve the Key

I'm attempting to query firebase, and I am encountering challenges when trying to retrieve a unique key from the record. While my filter is functioning correctly, I am struggling to identify the object property names within the data. The .key() method ...

Having too many node modules installed through npm in an Angular 2 quickstart project

Node/NPM versions: node: v5.4.0, npm: 3.3.12 I've embarked on the journey to learn Angular2 by diligently following the quick start tutorial on the official angular2 website. Angular2 Quickstart My package.json file mirrors that of the tutorial to ...

Mongoose: Unable to retrieve document files from the .chunk collection due to missing data field

I am attempting to remove the incomplete chunks from files that have not been fully uploaded to a MongoDB database. When uploading files directly to MongoDB, the Mongoose, Multer & GridFSBucket packages split media file data into two sub-collections for t ...

What are the steps for adding a PDF attachment to an email using nodemailer?

I want to send email with attachments dynamically using Nodemailer and jQuery in the front end. <script> $(document).ready(function () { var from, to, subject, text; $("#send_email").click(function () { to = $("#to").val(); s ...

Node can be used to minimize a static website

I have a website with static files like index.html, styles folder, scripts folder, and media folder. I want to create a script that minimizes all these files and organizes them in a dist folder while keeping the original structure. It seems like something ...

operating smoothly on local host, encountering issues on firebase

When I access the '/form' directory on my local host, the page renders correctly. However, when I deploy it on Firebase, I get a 404 error. Even if I change the 404 file itself, I still can't see any changes. I have tried clearing the cache ...

Issues with locking on a compact table when running basic queries are causing frustrations

One of our database tables is called DashboardItem, with the following list of columns: CREATE TABLE `DashboardItem` ( `id` int(11) NOT NULL AUTO_INCREMENT, `client_dashboard_id` int(11) NOT NULL, `type` varchar(100) COLLATE utf8mb4_unicode_ci DEFAUL ...

Using ExpressJS with the GET method to retrieve JSON data in conjunction with Angular version 4 and above

This inquiry may be a duplicate, I apologize for any repetition. My objective is to console.log JSON data from the "Server" folder. Please find the attached folder structure below. https://i.stack.imgur.com/uec4O.png server.js const express = require(&a ...

Types of Axios responses vary depending on their status codes

I am looking to create a specific type for axios responses based on the status code: types: type SuccessfulResponseData = { users: .... }; interface SuccessfulResponse extends AxiosResponse<SuccessfulResponseData, any> { status: 200; } ty ...

Struggling to locate the correct path for the CSS file in Express and Handlebars

As part of a student exercise, I am attempting to access an API containing information about presidents and style them using CSS. However, I am facing issues with linking the style.css file. I have tried various methods to change the path and public path ...

Data loss from AngularJS multipartForm directive when redirecting to different routes

Having trouble with an Excel file uploader and data parsing in the routes? It seems like the FormData is getting lost when sent through the $http service route. Any advice or experience on how to handle this issue would be greatly appreciated! Html View: ...

Protractor: Navigating two drop down menus simultaneously on a webpage, able to choose option from only one dropdown menu at a time

Currently, I am using Protractor to execute an automated script. On one of the pages, there are two drop down menus positioned above and below each other. The interesting thing is that both drop down menus appear to be identical except for their different ...

Interfacing Electron Frontend with Python Backend through seamless communication

Upon completing the development of a Python CLI app, it became apparent that creating an Electron frontend for better user interaction was necessary. What is the best way for the Electron app to communicate with the Python app when a user action occurs on ...

Image uploading using Multer with Node.js and Express

I've been struggling for days with Multer to upload an image. Despite trying various methods, I can't seem to get it right. I'm unsure how to utilize Multer to upload an image within my createUser function as illustrated below. My 'ser ...

Express app experiencing difficulties receiving request body sent by Postman

I have set up a basic post request in my code like this: app.post('/', (req, res) => { return res.status(200).json(req.body) }) However, when I try to make a post request using Postman, it returns an empty response {}. Below is the content ...

Why am I seeing back-end console errors that are related to my front-end?

Recently, I encountered an error message that prevents me from using 'import' in my front end code when trying to execute 'node index'. This issue never occurred before, and it only arose when I returned to this project. In my backend ...

Troubleshoot variable using EJS

Is there a way to set a global variable in EJS that can show/hide specific elements across all views without the need to redefine it each time? I am using node.js/express/ejs for my project stack and would like to know the best approach to achieve this. B ...