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

Cannot delete array from object populated by sails.js

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

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
}

我不知道这里发生了什么。

delete library.books; 不起作用,因为关联不是模型对象中的字段。关联实际上存在于 associations 对象中,并且 read/write 操作是通过自定义 getters/setters 完成的。您可以在 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() 然后删除关联字段也应该有效。