Can a for loop be implemented within a mongoose schema method?

Is there a way to modify this for loop so that it runs through the entire array instead of adding one by one?

Any suggestions?

EndorsedSkillSchema.methods = {
  async userEndorsedSkill(arr) {
    for (var i = 0; i < arr.length; i++) {
      const skill = await Skill.findOne({ _id: arr[i]._id });

      const s = skill.toJSON();

      this.skills.push(arr[i]._id);
      await this.save();
      pubsub.publish(SKILL_ENDORSED, { [SKILL_ENDORSED]: { ...s } });
      return {
        endorsed: true,
        ...s
      };
    }
  }
};

Answer №1

If you're looking to retrieve multiple documents based on an array of IDs, you could implement this solution using the find() method along with the {$in: ids} operator.

 const arr = [{_id:1},{_id:2},{_id:3}];

 const ids = arr.map(e=>e._id);

 Skill.find({_id: {$in: ids}}, function(err, result){
    //callback here maybe .insertMany()
 });

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

Creating dynamic JSX content in NextJS/JSX without relying on the use of dangerouslySetInnerHTML

I have a string that goes like "Foo #bar baz #fuzz". I'm looking to create a "Caption" component in NextJS where the hashtags become clickable links. Here's my current approach: import Link from "next/link"; const handleHashTag = str => st ...

Ways to retrieve the text linked to a checkbox

Is there a way to access the text associated with a checkbox using its attribute? For example, in the code below, I want to alert the user with "Selected -- TextXYZ" when the checkbox is clicked. <form id="idForm" class="classForm"> <input type ...

Is there a way for me to create a clickable link from a specific search result retrieved from a MySQL database using an AJAX

Currently, I am attempting to create an ajax dropdown search form that provides suggestions based on results from a MySQL database. The goal is for the user to be able to click on a suggestion and be redirected to the specific product. The code I am using ...

Unable to transfer files, encountering issues with PHP and AngularJS integration

I am currently working on uploading files using both AngularJS and PHP. For the AngularJS part, I am utilizing angular-file-upload from https://github.com/danialfarid/angular-file-upload. I suspect that the issue lies in my PHP code, as it fails to move ...

SpineJS combined with Express

Are there any recommended tutorials or case studies showcasing the integration of SpineJS and Express in applications? I have experimented with both technologies, but am currently facing some challenges. My backend is set up to run Express by using coffee ...

Combine the selected values of two dropdowns and display the result in an input field using Angular

I am working on a component that consists of 2 dropdowns. Below is the HTML code snippet for this component: <div class="form-group"> <label>{{l("RoomType")}}</label> <p-dropdown [disabled] = "!roomTypes.length" [options]= ...

Waiting for the code to execute once the filtering process is completed in Next.js using Javascript

I'm seeking a way to ensure that my code waits for the completion of my filter function before proceeding. The issue arises because my filter function, which incorporates another function called useLocalCompare, causes a delay in execution. This delay ...

Unusual behavior exhibited by AngularJS when working with Float32Arrays

After working with Float32Array values in AngularJS, I have noticed some unexpected behavior. During my testing, I encountered the following scenarios: angular.module("myApp", []).controller("myCtrl", function($scope) { $scope.n = 0.2; // Displays as 0 ...

A guide on reading an external JSON file using React

I'm trying to integrate an external JSON file into my React app. To demonstrate what I'm aiming for, I've provided a functional example on Codesandbox.io: https://codesandbox.io/s/morning-tdd-we2v3?file=/src/App.js Currently, the example ...

Display content exclusively within a modal specifically designed for mobile devices

I want to implement a feature where a button triggers a modal displaying content, but only on mobile devices. On desktop, the same content should be displayed in a div without the need for a button or modal. For instance: <div class="container&quo ...

Is your Bootstrap input displaying the has-error class with a glyphicon, but the alignment is not vertically centered?

What is the reason for the misalignment of glyphicon-warning-sign form-control-feedback vertically in the code below after applying font-size: 20px; to the label? <div class="container"> <div class="content align-left contact"> ...

Is it possible to add a jQuery-generated element to pure vanilla JavaScript?

I am facing a challenge in creating a new notification div when an event is triggered. Ideally, I would normally achieve this using jQuery by utilizing something like $("myDiv").append(newDiv). However, in this case, the item selector to which the new div ...

simulating interaction with databases within API routes

I am currently working on developing a full stack application using NextJS along with a MySQL database. Within my API routes, I interact with this database by making calls to various functions such as createOne(), which is responsible for creating new inst ...

How can I transfer data from two queries to Jade using Node.js (Express.js)?

I have a database with two tables - one for storing user information and another for managing friendship connections: setting up a friend list in mysql My goal is to create a profile page using Jade, specifically profile.jade: - each user in users ...

The functionality of the button is disabled once a pop-up JavaScript is implemented

I have encountered an issue with my HTML code that involves a button intended to hide certain content. The problem arose when I implemented a popup feature, causing the button to malfunction. Here is the JavaScript for the popup: $ = function(id) { retur ...

Instructions for obtaining and assigning a reference to a recently cached associated object within the Apollo client InMemoryCache

My data consists of a set of interconnected items like this: book { id ... related_entity { id ... } } Once Apollo caches it, there are two separate cache objects. The related_entity field on book points to an EntityNode object. Everything ...

Ensure that a group of checkboxes is mandatory

I currently have a series of checkboxes set up like so: <label>What is your preferred movie genre?</label> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="genre1" name="genre" ...

Using form submission to implement reCAPTCHA v3 in g-recaptcha

Is the Recaptcha API causing trouble? I have the key on both the submit button and the form tag, but it's only sending the sitekey without generating tokens. Any suggestions are welcome. You can either use the key in the form tag: <form method=&qu ...

Upon installation of Next.js, an error in the globals.css file quickly emerged, yet remarkably, it did not disrupt the code in

Here is the link to the repository: here. Once I created the next.js environment using the command "npx create-next-app@latest ./" and ran "npm run dev", I encountered the following error message:- ../../../#React Projects/My projects/causs/styles/global. ...

Error message: MongoDB - 'The function findOneAndDelete does not exist.'

I have the following code on my server: const Review = require('../models/reviewModel'); api.delete('/reviews/:reviewID', deleteReviewAndComments); // This function is responsible for deleting a review and all its comments const del ...