1

I am trying to update a document in a collection. I am particularly trying to update an array of Strings.The following is my Schema

var sampleSchema= mongoose.Schema({

        fullName   : String,
        email      : String,
        rolesTaken : [String],

});

I basically have an array of such schema's. I want to update the rolesTaken array for all of them. So I did the following

    var async = require('async');
    var ATmapping = require('path to Schema');

    ATmapping.find({},function(err,lists){
     if(err){
         console.log(err);
         return;
     }
     if(lists.length > 0){
      async.each(lists,function(list,callback){ 
        if(!list.rolesTaken){
              list.rolesTaken =[];
        }
       list.rolesTaken.push("Patient");
       list.markModified('rolesTaken');
       list.save(function(err,item){
            if (err){
                console.log(err);
            }

            console.log('Saved', item);
            callback();
       });
      });
     }
   });

I have browsed a lot and the most popular solution was to add markModified. But it doesn't seem to work in my case.When I added mongoose.debug i got the following

atmappings.update({ _id: ObjectId("59074b127adeef0004b84ac3"), __v: 7 }, { '$set': { rolesTaken: [] }, '$inc': { __v: 1 } })

As you can see the roles taken is empty despite me adding markmodified and save(). I would like to know if I am missing something which is preventing me from saving the values in the schema.

Thanks in advance.

RBN
  • 115
  • 3
  • 15

1 Answers1

0

Here is how I push a comment to a thread in one of my apps using mongoose.

Thread.findByIdAndUpdate(body.thread, { $push: { comments: comment.id }})

I simply find the thread by the id, then use the $push operator to push the comment id to the comments attribute where I populate later.

You can read more into the $push operator here (mongoose v3.4) https://docs.mongodb.com/manual/reference/operator/update/push/

Jordan
  • 157
  • 5
  • 17
  • Thanks for the answer. But somehow it doesn't seem to work – RBN Jun 02 '17 at 07:34
  • @RBN What have you tried? How have you implemented it? – Jordan Jun 02 '17 at 07:41
  • As you told i replaced i replaced my code to the following `ATmapping.findByIdAndUpdate(list._id,{ $push: {rolesTaken:role}},function(err,item){ console.log("pushed",item); });` where list is obtained by iterating using async.each – RBN Jun 02 '17 at 23:32
  • @RBN Hmm i've tested this and it's working for me here is my whole update statement, maybe it's because I'm catching the response at the end you're just going to have to test it on your end. `Thread.findByIdAndUpdate(body.thread, { $push: { comments: comment._id }}) .catch()` – Jordan Jun 04 '17 at 03:21