If the order of a Mongoose array is incorrect or an error occurs stating "Cast to string failed for value" when a schema for the array is specified

I'm currently working on a productivity app that includes a feature where users can select multiple items from a predefined list of tasks to create their own set of daily tasks. They also have the option to adjust the duration of each selected task by filling in an input field. In my 'user' Mongoose schema, I have a 'tasks' array where the user's selected tasks are saved under their details without modifying the default task list. However, I'm facing an issue where instead of saving key/value pairs for each selected task object in the database, the app is saving an array with keys in one object and values in another. Here is an example of the current saved data:

// If defined in userSchema:
// tasks: [] // Just an empty array

// Current data structure:
"tasks": [
    {
      "title": [
        "Title 01",
        "Title 02",
      ],
      "duration": [
        10,
        20,
      ]
    }
]

// Desired data structure:
"tasks": [
    {
      "title": "Title 01",
      "duration": 10
    },{
      "title": "Title 02",
      "duration": 20
    }
]

// If defined in userSchema:
// tasks: [tasksSchema] // Array of predefined objects
// Getting an error message
"error": {
    "message": "Cast to string failed for value \"[ 'Title 01', 'Title 02' ]\" at path \"title\"",
    "name": "CastError",
    "stringValue": "\"[ 'Title 01', 'Title 02' ]\"",
    "value": [
      "Title 01",
      "Title 02"
    ],
    "path": "title",
    "reason": null
}

Here is the remaining code for my model, controller, and view:

// My model
const tasksSchema = new mongoose.Schema({
  _id: {
    type: mongoose.Schema.ObjectId,
    ref: 'Tasks',
  },
  title: {
    type: String,
  },
  duration: {
    type: Number,
  },
});

const userSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      trim: true,
      required: true,
    },
    tasks: [tasksSchema],
  },
  {
    timestamps: true,
  });

module.exports = mongoose.model('User', userSchema);

// My controller
exports.updateUser = async (req, res, next) => {
  try {
    const user = await User.findOne({ _id: req.params.id });

    await User.findOneAndUpdate(
      { _id: req.params.id },
      req.body,
      { new: true, runValidators: true },
    ).exec();

    if (!user) {
      return res.status(404).json({
        success: false,
        error: 'no User found',
      });
    }

    return res.redirect('back');
  } catch (err) {
    if (err.name === 'ValidationError') {
      const messages = Object.values(err.errors).map((val) => val.message);
      return res.status(400).json({
        success: false,
        error: messages,
      });
    }
    return res.status(500).json({
      success: false,
      error: err,
    });
  }
};

// My view (Pug/Jade)
each item in user.tasksList || [] // This list is generated from a model 'Tasks'
  li.sortableItem.ui-state-default.list-group-item(value=item._id id=`id_${item._id}` name="tasks")
    span
      input#title(type='text' name="tasks[title]" value=item.title)
    span 
      input#duration.col-sm-2.input-sm.text-gray(type='number' name="tasks[duration]" value=item.duration)

Any insights on what I might be doing wrong would be greatly appreciated! Thanks!

Answer №1

In case the framework lacks a straightforward method to return these inputs as an array of objects, you can utilize the map function to generate an array of objects from the individual arrays before creating the user:

tasks = tasks[0].title.map((e,i) => ({"title":e,"duration":tasks[0].duration[i]}))

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

Array of Xcode images for the next button

I am currently working on developing an app using Xcode 4 with storyboarding. The structure of my project includes: 1 table view controller 1 detail view controller with 4 buttons, and a total of 6 images (1-1.jpg/1-2.jpg/1-3.jpg, and 2-1.jpg/2-2.jpg/2 ...

What could be the reason my span is not altering color as I scroll?

Important HTML Knowledge <section class="home" id="home"> <div class="max-width"> <div class="home-content"> <div class="text-1">Hey t ...

Tips on developing a limited directive?

Currently, I am experimenting with AngularJS and NG-Table and facing a challenge that I cannot seem to resolve: My issue involves displaying a collection of User objects from a Django application in an NG-Table. One of the attributes of the model is a boo ...

Designing Interactive Circular Dates on Website

Currently, I am working on a webpage using HTML, CSS, JavaScript, and PHP. The goal is to design a page that features 7 circles representing the current date and the next 6 days. Users should be able to click an arrow to navigate to the following 7 days. ...

Utilize dropdown1 to dynamically populate dropdown 2 in AngularJS

Here is the HTML code snippet I am currently working with: <select ng-controller="category" ng-model="selectedTestAccount" ng-options="c.category for c in categories track by c.categoryID" ></select> <select ng-controller="subcategory" ng ...

Can you provide guidance on implementing structured data jsonLD in a Next.js 13 application's router?

I have been struggling to implement structured data in my Next.js 13 (app router) application and have not been able to find the correct method. The next-seo package is also throwing errors for me. When I tried using next-seo, I encountered this error: ...

The body of the POST request appears to be void of any

Whenever I make a request using curl or hurl, an issue arises. Despite req.headers['content-length'] showing the correct length and req.headers['content-type'] being accurate, req.body returns as {}. Below is the Hurl test: POST http:/ ...

The AJAX request is now being "canceled" since the website is up and running

After successfully running AJAX requests on my new version, which was in a sub directory of my site (www.staging.easyuniv.com), I moved the site to the main directory to make it live (www.easyzag.com). Although everything seems to be functioning properly, ...

Adding pictures to the select choices in bootstrap-vue

How can I include images in the dropdown list of a Bootstrap-vue select component like the example shown in the image below? https://i.sstatic.net/5PQWd.png ...

The icons from MaterializeCSS are not displaying correctly on the navbar within an Angular 7 project

Having an issue implementing MaterializeCSS Icons on the navbar. The arrow-drop_down icon is not displaying correctly, showing only text instead. Oddly enough, the icons render properly on other pages except for the app.component.html file. I attempted to ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

When trying to run the "npm start" command, I encountered a syntax error that specifically mentioned the use of

Every time I attempt to run the npm start command, I encounter the following error: I have followed the steps provided in this link: https://github.com/kriasoft/react-starter-kit/blob/master/docs/getting-started.md Could you please advise on how to resolve ...

Top method for developing a cohesive single-page application

Many websites are incorporating JSON data in string format within their page responses, along with HTML: For example, take a look at https://i.sstatic.net/bDU7X.png The benefit of rendering JSON in string format within the page response is that it allow ...

What is the best way to retrieve different data from the Firebase database within a cloud function?

Currently, I am utilizing the Firebase real-time database and attempting to establish a trigger for when a field named ignore is added to my DB. However, before proceeding with this trigger, I need to access another set of data within the database in order ...

Should you utilize publications or categorize into collections for better performance?

I have a collection that only has two specific queries performed on it. For example, Cars.find({color: 'red'}); and Cars.find({color: 'blue'}); I'm considering whether I should create separate RedCars and BlueCars collections ins ...

The z-index overlapping problem in webkit browsers is a result of Angular 7 animations

I have implemented staggered animations in my Angular 7 application to bring elements to life upon page load. However, I am facing a strange z-index problem with one of my components. Here is the animation code: @Component({ selector: 'track-page& ...

Enabling Bootstrap modal windows to seamlessly populate with AJAX content

I'm currently in the process of crafting a bootstrap modal that displays the outcome of an AJAX request. Below is my bootstrap code: {{--Bootstrap modal--}} <div id="exampleModal" class="modal" tabindex="-1" role="dialog"> <div class="m ...

Creating a thumbnail with a close button using an image

My code is available at the following link: https://codepen.io/manuchadha/pen/PBKYBJ In this form I have created, I am trying to implement an image upload feature using a file input. The goal is to display a thumbnail of the selected image below the file ...

Remove an element from an array in JavaScript when a condition is met in an if/then statement

I am currently working on a function that loops through elements in an array and removes values outside of a specific range. However, I have encountered an issue where using the pop method always removes the last element in the array rather than the intend ...

Troubleshooting: Issue with passing variables from jQuery $.ajax to PHP

I am working on creating a 'show more' button using jQuery AJAX. The button has a loaded attribute like this: <button type="button" class="smbt btn center-block" data-loaded="3">Show More</button> In my JavaScript file, I have the f ...