无法从sails.js填充的对象中删除数组

时间:2015-05-27 10:26:30

标签: javascript node.js sails.js waterline

我无法delete或更改books对象的library属性值。

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);
    });

我的图书库和createdBy模型就像

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

我无法弄清楚这里发生了什么。

1 个答案:

答案 0 :(得分:5)

delete library.books;不起作用,因为关联不是模型对象中的字段。关联实际上存在于associations对象中,读/写操作通过自定义getter / setter完成。您可以在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
  });
};

希望有所帮助。

这会导致问题吗?这可以通过不首先填充关联来避免。执行model.toObject()model.toJSON()并删除之后的关联字段也应该有效。