0

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?

ZeMoon
  • 20,054
  • 5
  • 57
  • 98
saurabh vyas
  • 115
  • 1
  • 10
  • Did you try `findAndModify` (https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/) ? – AboulEinein Feb 08 '16 at 12:31
  • Or maybe you can use $in to find documents matching the multiple ids (http://stackoverflow.com/questions/8303900/mongodb-mongoose-findmany-find-all-documents-with-ids-listed-in-array?answertab=votes#tab-top) then modify the each document – AboulEinein Feb 08 '16 at 12:33
  • yeah it was helpful thanks – saurabh vyas Feb 08 '16 at 14:41

1 Answers1

0

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,

narainsagar
  • 1,079
  • 2
  • 13
  • 29