Update of multiple documents with mongoose fails

Update of multiple documents with mongoose fails

By : Philip Ward
Date : November 22 2020, 02:42 PM
around this issue I have setup small example which works as expected, first i called start() to create some users then update()
code :
var mongoose = require('mongoose'); //v4.2.7

var userSchema = mongoose.Schema({
    deleted: Number,
    name: String

var User = mongoose.model('user', userSchema);



function start(){

    for (var i = 0; i < 5; i++) {
        var user = new User({
            deleted: 1,
            name: i
        console.log('user ---> ', user);      

    User.find({}, function(err, docs){
        console.log('found ---> ', err, docs);



function update (){
    User.update({deleted:1}, {$set: {deleted: 0}}, {multi:true}, function(err, numAffected){
        console.log('updated ---> ', err, numAffected);
function update (){
    // this doesn't work
    User.where({deleted:1}).update({$set: {deleted: 0}}, {multi:true}, function(err, numAffected){
        console.log('updated ---> ', err, numAffected);

Share : facebook icon twitter icon
how can i update multiple documents in mongoose

how can i update multiple documents in mongoose

By : Alex Grenier
Date : March 29 2020, 07:55 AM
I wish this helpful for you Currently I believe that update() in Mongoose has some problems, see: https://groups.google.com/forum/#%21topic/mongoose-orm/G8i9S7E8Erg and https://groups.google.com/d/topic/mongoose-orm/K5pSHT4hJ_A/discussion.
However, check the docs for update: http://mongoosejs.com/docs/api.html (its under Model). The definition is:
code :
Model.update = function (query, doc, options, callback) { ... }
Model.update = function ({}, {cid: ''}, {multi: true}, function(err) { ... });
Model.updateMany = function (query, doc, callback) { ... }

Model.updateMany = function ({}, {cid: ''}, function(err) { ... });
Update multiple documents by id set. Mongoose

Update multiple documents by id set. Mongoose

By : LouFoo
Date : March 29 2020, 07:55 AM
like below fixes the issue Most probably yes. And it is called using $in operator in mongodb query for update.
code :
   { _id: { $in: ['id1', 'id2', 'id3'] } },
   { $set: { visibility : yourvisibility } },
   {multi: true}
Update multiple documents by providing documents in body, mongoose/mongodb

Update multiple documents by providing documents in body, mongoose/mongodb

By : vikas rana
Date : March 29 2020, 07:55 AM
hop of those help? Try using the update command along with the "$in" operator:
code :
var ids= [];
for (var i=0 i<input.body.length; ++i) {

mongoose.model('person').update( {id : {"$in":ids}}, {active:false} , {multi: true} , function(err,docs) { ... });
Mongoose update multiple documents doesn't update anything

Mongoose update multiple documents doesn't update anything

By : Agezew Tesfaye
Date : March 29 2020, 07:55 AM
it should still fix some issue After a few hours spend trying to find out where the error was and why it wasn't updating the database, I found out it actually did update the database. The problem was that I was checking the update in mongo shell and after I updated it over nodejs post request, it didn't appear in the shell as updated. However when I console.log() the labels, it was updated. So I investigated the problem further and I found out that the the problem wasn't the mongo shell, but incorrect usage of mongoose command update. I was missing the callback argument. After adding the callback function, the data were updated in the mongo shell immediately.
So instead of doing:
code :
Label.update({'_id': { $in: post.labelIds }}, {$addToSet: {postIds:req.body.id}}, {multi: true})
Label.update({'_id': { $in: post.labelIds }}, {$addToSet: {postIds:req.body.id}}, {multi: true}, function(err, affected) {
      // After successful update, redirect here to another page...
Label.update({'_id': { $in: post.labelIds }}, {$addToSet: {postIds:req.body.id}}, {multi: true}).exec()
To update multiple documents in mongoose (Node JS)

To update multiple documents in mongoose (Node JS)

By : JMC
Date : March 29 2020, 07:55 AM
this one helps. I'd like to update multiple documents with query that is made by object array. However I found that only one documents had been changed. , Use bulk find and update,
code :
var bulk = db.Model.initializeUnorderedBulkOp();
var vm = {
  name: "robert",
  category: "media"

for (var i in split) {
  var pk = {
    "_id": split[i],
    "id": user.id
    $set: vm

Related Posts Related Posts :
  • Node.js Winston elastic search logger
  • What IP address should mongoose connect to in production mode?
  • Cannot install mongoose using npm install
  • should I store jwt token in user table or in separate table?
  • require all folders as modules inside folder?
  • Node AWS S3 getObject firing httpDone before file stream completes
  • babel-jest ES2015 import statements
  • Scheduling a lot of tasks on back-end, Node.js
  • Node.js, Mongo async.js inserts and queries
  • Unexpected String when using BlueMix's Node-RED editor and MQTT->Debug Node
  • Node.js signing and verifying log files digitally using OpenSSL
  • HTTP Proxy( Node.js) Not Performing Proper SSL Verification
  • Can't kill NodeJS app
  • How to unit test a tool that uses command-line-args
  • MEAN Stack yo meanjs returns errors when creating new project
  • .findOne not passing results to callback
  • Reading from a file in node.js
  • Error: invalid_request getToken
  • NPM not found when using NVM
  • Unhandled 'error' event with fs in node js
  • CircleCI : $ npm test failing
  • Freshbook style email template using Nodejs
  • nodejs + mongoose - query aggregate
  • Deal with timeout exceptions in an async loop
  • Creating a command line application using Node
  • I cannot get url from a website using nodejs
  • MongoDB - OneToMany with foreign key in child
  • prepared statements node-postgresql error with null result
  • if 800k record takes 50 secs all http pending request in queue would block for 50 sec as sever become ideal
  • Detecting OS version and using the right PhantomJS binary
  • Uninstall nodejs installed from binary distribution files
  • NPM installing package with multiple folders for package
  • De-tangling logs for tasks running in Node JS
  • Sequelize with sqlite dialict on node v5
  • Authentication with hapi-auth-cookie not setting session
  • how to set query variables on server response
  • Node 'request' method doesn't execute
  • WebStorm code completion for Node shows too many options
  • Trying to send header in node
  • Node-webkit: using the same codebase for web- and desktop application
  • socket.io can't connect to server
  • Deploying a Node.js(+MongoDB) app with Heroku, always Local Port
  • Share HTTP port 80 with apache webserver and Node.js REST server
  • MongoDB: How to find a document sharing a list element with specified list
  • Use Node.js as Shell
  • How to run a node.js app in background on Azure
  • Error: Cannot find module 'npm-registry-client'
  • How to install older version of node.js on Windows?
  • force jspm to install newest version
  • Querying a Global Secondary Index in dynamodb Local
  • how to access db from node.js middleware
  • How to tell Node.JS to use modules from global by default?
  • Determine the CPU in use of a process nodejs
  • browserify bundle electron app main process file
  • How do I reset the expiration date of a document in Mongoose?
  • How to implement Async with Mongoose method
  • Deployment of individual nodes in Node-RED
  • Install cordova on windows 10
  • Run node server using gulp task
  • Server-side React: Babel doesn't transform JSX on the server neither on the fly not manually. Why?
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co