Skip to content Skip to sidebar Skip to footer

Toggle Boolean Value Of Subdocuments

i am trying to toggle the boolean value inside an array which is a collection of objects, problem is that field is being triggered for two both objects inside array, and i want to

Solution 1:

I cannot see the result that you claim, which means it works for me and the rest of the world. Here is the abridged listing as a single script example:

varasync = require('async'),
        mongoose = require('mongoose'),
        Schema = mongoose.Schema;

    mongoose.connect('mongodb://localhost/test');

    var invitationSchema = newSchema({
      "ID": { "type": Schema.Types.ObjectId },
      "Accepted": Boolean
    });

    var userSchema = newSchema({
      "Invitation": [invitationSchema]
    });


    varUser = mongoose.model( 'User', userSchema );

    User.find({},'Invitation',function(err,docs) {
      if (err) throw err;
      var results = [];

      async.each(docs,function(doc,callback) {
        async.each(doc.Invitation, function(invite,callback) {
          User.findOneAndUpdate(
            { "_id": doc._id, "Invitation._id": invite._id },
            { "$set": { "Invitation.$.Accepted": !invite.Accepted } },
            function(err,doc) {
              results.push(doc);
              callback(err);
            }
          );
        },callback);
      },function(err) {
        if (err) throw err;
        console.log( results.slice(-1)[0] );
        process.exit();
      });
    });

So that clearly "toggles" both values as requested and works perfectly.

This is the result from me on one shot:

{ _id:54be2f3360c191cf9edd7236,
  Invitation:
   [ { __v:0,
       ID:54afaabd88694dc019d3b628,
       __t:'USER',
       _id:54b5022b583973580c706784,
       Accepted:true },
     { __v:0,
       ID:54af6ce091324fd00f97a15f,
       __t:'USER',
       _id:54bde39cdd55dd9016271f14,
       Accepted:true } ] }

Post a Comment for "Toggle Boolean Value Of Subdocuments"