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

vus*_*san 1 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);
    });
Run Code Online (Sandbox Code Playgroud)

我的图书库和创建的模型就像

createdBy: {
    model: "createdBy"
},
books: {
    collection: "books",
    via: "library",
    dominant: true
}
Run Code Online (Sandbox Code Playgroud)

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

Dár*_*rio 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
  });
};
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.

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