Looking to locate an array within a schema using its unique identifier

const FormFieldsSchema = new Schema({
  formName: {
    type: String,
    required: true
  },
  fields: [
    {
      fieldLabel: {
        type: String,
        required: true
      },
      inputData: [{
        type: mongoose.Schema.ObjectId,
        ref: "UserData"
      }]
    }
  ]
});

Hey everyone, I'm facing an issue with a schema where fields is an array and each item has an _id property. I want to update a specific array item based on the _id value, but so far I've been unsuccessful. I've tried using findByIdAndUpdate, as well as parent.inputData.id(_id);, but no success yet. Any suggestions or ideas on how to achieve this?

Answer №1

To simplify querying, convert the array content into a separate model and interact with it directly.

When using findByIdAndUpdate on FormFieldsSchema, remember that it searches for the _id of FormFields, not the content of the fields array.

const FieldSchema = new Schema({
      fieldLabel: {
          type: String,
          required: true
      },
      inputData: [{
          type: mongoose.Schema.ObjectId,
        ref: "UserData"
      }]
})

Update field to fields: [FieldSchema] and don't forget to export FieldSchema as a model.

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 battle between ui-sref-active and $state.includes() is a topic of

I am attempting to highlight the clicked area by adding an active class using ui-sref-active. Unfortunately, it is not working with $state.includes(), even though I can see its value as true in the controller. Can someone assist me with this issue? See th ...

Disable all components on the web page using the Wicket DisableComponentListener

When using an ajax button in my Wicket application, the following code works perfectly: @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); attributes.getAjaxCallListeners().add ...

Tips on preventing the initial undefined subscription in JavaScript when using RxJS

I am having trouble subscribing to an object that I receive from the server. The code initially returns nothing. Here is the subscription code: ngOnInit() { this.dataService.getEvents() .subscribe( (events) => { this.events = events; ...

Completing online form text entries in WebView without the need for identifying elements

I am currently working on a project to automate filling out an online login form using local string variables. This is the progress I have made so far: web = (WebView) findViewById(R.id.webview); WebSettings webSettings = web.getSettings() ...

JavaScript: Retrieve an array that is both unique and sorted

I have an array that contains duplicate items. My goal is to filter out these duplicates and return only the unique items, sorted based on their frequency of occurrence in the initial array. const initialArr = [ { id: 1 }, { id: 1 }, ...

Using Javascript outside of the AngularJS environment

I am trying to utilize Javascript functions outside the controller in Angular JS instead of using a service within a module. Is this allowed? For instance: var UrlPath="http://www.w3schools.com//angular//customers.php" //this section will store all the f ...

Testing JavaScript performance using the V8 engine

function add(x, y) { return x + y; } console.time("clock1"); for (var i = 0; i < 90000000; ++i) { add(1, 2); add('a','b'); } console.timeEnd("clock1"); function combineText(x, y) { return x + y; } fu ...

Incorporating the Microsoft Teams Embedded Share Button within a React-based web application

Recently, I successfully implemented the Microsoft Teams Embedded Share Button in React by following these steps: Step 1: First, I included the launcher.js script on my web app: I simply added this script to a useEffect hook: <script async defer src=& ...

Merging Objects and inserting them into an array - Harnessing the power of JavaScript and

Having various objects stored in an array, each with a unique labelId assigned to them. Whenever there are matching label ids, the goal is to merge these objects together by consolidating some values inside a new combined object array. [ { fi ...

Exploring pagination with Meteor's MongoDB

In my Meteor app, I am implementing pagination with infinite scrolling. When the user reaches the bottom of the page, I fetch the next batch of data using Collection.find({"offset": {$gte: currentOffset}}, {limit: limit}). However, the issue with this ap ...

Retrieving a randomly selected item from MongoDB with Loopback

I've scoured the internet in search of a solution for obtaining multiple random objects from MongoDB using Loopback. The main purpose behind my search is to implement a feature like "Interested in this book/recommendation", where 4-5 books are displa ...

Instructions for loading custom field data from a WordPress post using ajax

Even though I am not proficient in PHP programming and unfamiliar with data fetching, I am attempting to create a template that dynamically loads custom field values of posts via AJAX in WordPress. The rationale behind using AJAX for loading these values ...

I'm trying to access my navigation bar, but for some reason, it's not allowing me to do so

Having trouble getting the navigation bar to open. I have set it up so that when clicked, it should remove the hide-links tag, but for some reason, it does not toggle properly and keeps the ul hidden. import React from "react"; import { NavLink } ...

The MongoDB SocketException Error: Connection refused has occurred

Currently, I am working on a project that involves using MongoDb in combination with ExpressJS to create a RESTful API. I have come across an issue where the MongoDb server abruptly stops while performing a long insert operation in a loop without closing t ...

Compendium and Collection

Hey there, I'm relatively new to Node.js and have encountered an issue with dictionaries and arrays. What I'm trying to achieve is accessing courseid and coursename. data = [ { name: "Ole Nordmann", pin: 1331, Job: ...

Unpredictable Redirection when URL is Clicked using PHP or Javascript

Looking to send users to a random URL from a specific list? For instance: With 3 URLs available - Google.com, Facebook.com, and Yahoo.com <a href="<?php $sites[array_rand($sites)] ?>">Click here</a> Upon clicking the link, users will ...

Creating Dynamic Lists with React Native

<Search ref="search_box" onSearch={this.onSearch} backgroundColor="white" cancelButtonTextStyle={{ color: "red" }} placeholder="Search Food..." ...

Steps for creating a dynamic validation using a new form control

I have an item that needs to generate a form const textBox = { fontColor: 'blue', fontSize: '18', placeholder: 'email', name: 'input email', label: 'john', validation: { required: false } ...

Implementing JavaScript to Retrieve and Insert Full HTML Tags into a Textarea

I am currently trying to extract an HTML source code value and insert it into a specific textarea or div upon clicking a button. However, I am encountering issues where I am not receiving the entire HTML tags - it seems to begin with a Meta tag and is remo ...

Encountered an error with the post request in expess.js: TypeError - Unable to access the property 'fullName' as it is undefined

Hey everyone, I'm new to Express and having trouble posting data from Postman. The error message I'm getting is "TypeError: Cannot read property 'fullName' of undefined". Does anyone have any suggestions on how to fix this? Thank you! ...