Meteor:插入时的过滤属性不起作用 [英] Meteor: Filtering properties on insert doesn't work

查看:101
本文介绍了Meteor:插入时的过滤属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想过滤来自客户端但在创建新文档时不需要的属性。我试图使用下划线的_.pick(),但似乎我不能覆盖 doc

I'd like to filter properties that are coming from the client but not wanted when creating new documents. I tried to use underscore's _.pick() but it seems like I can't override 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;
  }
});


推荐答案

/ code>

doc = _(doc).pick(Entries.allowed);

您正在覆写 doc variable ,使其不再指向实际的 doc 对象。

You're overwriting the doc variable so that it no longer points to the actual doc object. What you want is to change the object itself.

您需要 delete all未列入白名单的 doc 属性。示例实现:

You need to delete all the doc properties that are not whitelisted. Example implementation:

insert: function(userId, doc) {
  var keys = _.keys(doc);
  keys = _.difference(keys, Entries.allowed);
  _.each(keys, function(key) {
    delete doc[key];
  });
}

这篇关于Meteor:插入时的过滤属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆