我想过滤来自客户端但在创建新文档时不需要的属性。我尝试使用下划线的 _.pick() 但似乎我无法覆盖doc。
Meteor.Collection.prototype.addTimestamps = function () {
this.deny({
insert: function(userId, doc) {
doc.createdAt = Date.now();
doc.updatedAt = Date.now();
return false;
},
update: function(userId, doc, fieldNames, modifier) {
modifier.$set.updatedAt = Date.now();
return false;
},
});
};
Entries.addTimestamps();
Entries.allowed = ['_id', 'content', 'createdAt', 'updatedAt'];
Entries.allow({
insert: function (userId, doc) {
doc = _(doc).pick(Entries.allowed);
doc.userId = userId;
return !! userId;
},
update: function (userId, doc, fieldNames, modifier) {
return doc.userId === userId;
},
remove: function (userId, doc) {
return doc.userId === userId;
}
});
最佳答案
通过写入行中的doc
doc = _(doc).pick(Entries.allowed);
您将覆盖 doc
变量,以便它不再指向实际的 doc
对象。您想要的是更改对象本身。
您需要删除
所有未列入白名单的doc
属性。实现示例:
insert: function(userId, doc) {
var keys = _.keys(doc);
keys = _.difference(keys, Entries.allowed);
_.each(keys, function(key) {
delete doc[key];
});
}
关于javascript - Meteor:插入时过滤属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23395189/