vusan
vusan

Reputation: 5331

Cannot delete array from object populated by sails.js

I cannot delete or change the value of books attribute of library object.

Library.findOne(12).populate('books').populate('createdBy').exec(
    function(err,library) {

        delete library.createdBy;
        //worked

        delete library.name;
        //worked

        delete library.books;
        //no effect

        library.books = [];
        //worked

        library.books = [{a:'any val'}];
        //just like library.books=[]

        console.log(library);
    });

My model for library for books and createdBy is like

createdBy: {
    model: "createdBy"
},
books: {
    collection: "books",
    via: "library",
    dominant: true
}

I cannot figured out what is happening here.

Upvotes: 1

Views: 634

Answers (1)

Dário
Dário

Reputation: 2082

delete library.books; does not work because associations are not fields in the model object. Associations actually live in an associations object and read/write operations are done through custom getters/setters. You can see more about this behaviour in waterline/model/lib/internalMethods/defineAssociations.js#L109:

Define.prototype.buildHasManyProperty = function(collection) {
  var self = this;

  // Attach to a non-enumerable property
  this.proto.associations[collection] = new Association();

  // Attach getter and setter to the model
  Object.defineProperty(this.proto, collection, {
    set: function(val) { self.proto.associations[collection]._setValue(val); },
    get: function() { return self.proto.associations[collection]._getValue(); },
    enumerable: true,
    configurable: true
  });
};

Hope that helps.

Is this causing a problem? This can be avoided by not populating associations in the first place. Doing model.toObject() or model.toJSON() and delete the association field afterwards should also work.

Upvotes: 5

Related Questions