Updating multiple documents in mongoose using Node JS is a breeze

When attempting to update multiple documents using a query generated from an object array, I encountered an issue where only one document was actually modified.

var split = num.toString().split(',');
var list = new Array;
for ( var i in split ) {
    var pk = {
        "_id" : split[i],
        "id" : user.id
    }
    list.push(pk);
}

var vm = {name:"robert",category:"media"};

database.bookModel.findOneAndUpdate(list, vm, { multi: true }, function (err, result) {
....

I have tried the above approach to updating multiple documents but it seems to only affect a single record. Is there a mistake in my code? Is there a way to utilize criteria with an object array?

Answer №1

If you switch from 'findOneAndUpdate' to 'update', you will be able to update multiple documents at once. Give it a try!

Answer №2

Utilize the power of bulk find and update methods,

var bulkOperation = db.Model.initializeUnorderedBulkOp();
var data = {
  title: "robert",
  type: "video"
};

for (var index in splitData) {
  var query = {
    "_id": splitData[index],
    "userId": user.userId
  }
  bulkOperation.find(query).update({
    $set: data
  });
}

bulkOperation.execute();

Answer №3

For your query to be successful, modify it as follows:

database.bookModel.updateAll(records, viewModel, {
    multiple: true
}).then(() => {
    res.status(200).json({
        message: 'Updated data is now live!'
    })
}).catch((error) => {
    res.status(500).json({
        issue: 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

Node/Express API returning empty body when being accessed through fetch or axios requests

Currently working on integrating an API call in a React app using Node/Express. No matter where I place the fetch/axios call, the parsed body always shows up as undefined in my controller. Yesterday, I was experimenting with fetch but decided to switch to ...

Utilize middleware nesting in Express.js

I am interested in implementing middleware to validate requests based on a RAML file. Below is an outline of my current code: // dependencies let resources = require('osprey-resources'); let errorHandler = require('request-error-handler&apo ...

Having trouble with Socket.io and its io.emit() method refusing to work? If communication from server to client isn't going smoothly, you may need a solution for sending data from the server to

My latest project is a document converter program that utilizes LibreOffice to convert documents to PDF format. Here's my server running on localhost:3000 import express from "express"; import bodyParser from "body-parser"; import ...

Display inputs based on selections made on the settings page

I'm currently trying to strategize a way for users to navigate to /settings and select certain checkboxes. Then, when they move on to /new, they will only encounter input fields that pertain to the checkboxes checked in /settings. The process of achi ...

Passing Express routes through an nginx proxy

When I visit with the provided configuration and code, instead of just '/yo', Express is searching for a '/api/yo' route. How can I configure NGINX so that when express sees , it thinks it's '/yo'? server { listen ...

Error encountered in NodeJS after refreshing the node server

I am currently in the process of developing a web application using Node.js, Express framework, and EJS templates. Below is the code snippet for my server setup: const express = require('express'); const app = express(); const PORT = process.en ...

When working with Express and Axios together, it is important to note that Axios may not handle

I've simplified my use case for testing purposes - clicking a button triggers an UPDATE put request using an axios API. While post, get, and delete requests are functioning correctly, my PUT method consistently returns a 404 Not Found error. It seems ...

What is the best way to return JSON from a 403 error using Express?

Express has the ability to handle errors, and you can send back JSON data when returning a 403 status code like this: let error = {errorCode:"1234"} res.sendStatus(403, {error: error}); To catch and inspect the error in your frontend JavaScript, you can ...

Get the csv document from the backend

I am currently working on generating a CSV file, inserting data into it, and then downloading it from the browser. The process involves creating the CSV file in the backend using Express.js and sending the download link to the frontend built with React.js. ...

Is there a way to fix the error "The requested resource does not have the 'Access-Control-Allow-Origin' header" within Express using Firebase functions?

Trying to send an email through nodemailer using Firebase functions, but encountering errors. The data for the email will come from a form. Error message: Access to XMLHttpRequest at 'my-firebase-functions' from origin 'my-angular-web-app&a ...

The jade code is causing an error to be displayed

The following Jade code seems to be malfunctioning. head script(src='http://d3js.org/d3.v3.min.js') script(src='http://dimplejs.org/dist/dimple.v2.1.0.min.js') body script(type='text/javascript') var svg ...

Unidentified authorization token in React/Express

I've encountered an issue while implementing JWT authentication on a login/registration system. After a successful login/registration, I am setting a user token in localStorage. The problem arises when I inspect my localStorage and find that the user ...

Is it possible to include a parameter in module.exports?

A module in my application runs a query and uses express to display the results. module.exports.runQuery =function(req,res){ //establishing connection connection.on('connect', function(err) { console.log("success"); //if connec ...

Navigating hierarchical data structures with mongoDB and mongoose: finding the perfect schema

Just starting out with mongoDB and using mongoose to create a schema for my node project. I've realized that using embedded data instead of by reference is the way to go in my scenario (http://docs.mongodb.org/manual/core/data-modeling-introduction/) ...

Guide on adding logout feature with jsonwebtoken in node.js

One common approach is to delete the browser's cookie first. However, I am interested in learning how to destroy tokens from the server side or how to verify logout functionality from the server side. ...

Sending files in Express causes issues

I keep receiving the following message: express deprecated res.sendfile: Use res.sendFile instead Here is the code snippet in question: app.get('/*', function (req, res) { var myUrl = req.url.split('/')[1]; myownfunction(myUrl ...

Issue: unable to establish connection. Address is already in use. Attempted all possible solutions

Struggling to resolve the port already in use issue. I've been attempting to terminate the process using the PID, but it keeps reappearing. When I try to modify the port in the main JavaScript file, the command fails to proceed and becomes stuck, req ...

Combining GraphQL: stitching and uniting

I am looking for a way to consolidate multiple graphQl services with the same schema into a single read-only service that exposes data from all services. This means aggregating data from different domains and combining it into one unified dataset: ---- do ...

What steps can you take to intentionally cause errors in a Node Express application in order to capture them in Sentry?

Currently, I am utilizing log4js logger with node express to log errors to a file. However, the log files are quite difficult to interpret and I rarely look at them. I recently integrated Sentry into my project. I want to be able to manually send errors t ...

What are the consequences of submitting a form to a different website through POST method?

Dealing with a CMS that does not offer an easy way to add a NodeJS route for handling form data can be quite challenging. I'm considering the following setup - would this be considered bad practice or unsafe? Server 1 (Ghost CMS) : www.domain.com &l ...