saurabh vyas February 2016

How do I update more than one mongodb records at once?

So I am creating a basic todo app using express and mongodb at the backend, I have a task schema that looks like this :

var taskSchema = mongoose.Schema({
    task: String,
    time:Date,
    done:Boolean,
    id:Number   
});

By default the done is not set, but in the frontend I have a unordered list and bunch of lines and each line has a checkbox next to it , I want that when the user selects a list of tasks from checkboxes and click on done button it should go as a post request and mongodb should update all tasks at once , is it possible? Is my approach correct?

Answers


narainsagar February 2016

Suppose this is the data in the db:

[
 {
   _id: "1",
   task: 'hello1',
   time: '11-02-2015',
   done: false
 },
 {
   _id: "2",
   task: 'hello2',
   time: '11-02-2015',
   done: false
 },
 {
   _id: "3",
   task: 'hello3',
   time: '11-02-2015',
   done: false
 },
 {
   _id: "4",
   task: 'hello4',
   time: '11-02-2015',
   done: false
 },
 {
   _id: "5",
   task: 'hello5',
   time: '11-02-2015',
   done: false
 }
];

So you will be sending all selected tasks (let's call it an array) via POST request on when Done is clicked.

Array will be contain list of taskIds like this:

var tasksArr = [
  "1", "2", "3", "4"
];

So you will be doing something like this in your route function..

var bulk = TaskSchema.collection.initializeUnorderedBulkOp();

for (var taskId in tasksArr) {
   bulk.find({_id: taskId}).update({
     '$set': {done: true}
   });
}

bulk.execute(function(err, bulkres) {
   console.log('modified:', bulkres.nModified);
});

Hope this helps.

Cheers,

Post Status

Asked in February 2016
Viewed 1,151 times
Voted 11
Answered 1 times

Search




Leave an answer