如何在Meteor中添加或删除服务器端的收集文档字段?

时间:2013-10-26 16:55:59

标签: meteor

我需要在allow或deny方法中插入或更新之前向doc添加或删除字段。我曾假设转换函数会提供所需的功能。

meteor docs state

  

“可选的转换功能。文件将通过   此函数在从fetch或findOne返回之前和之前   传递给观察,允许和拒绝的回调。“

每当我尝试从函数转换并返回文档时,无论是允许还是拒绝,文档的转换版本都不是插入到mongodb中的。我尝试通过2种策略进行转换。

策略1

var ts = new Date(); 
return _.extend(_.pick(doc, 'name', 'discounts', 'locations', 'url_map', 'client_updated_td', '_id'), {   created_td:
ts,   updated_td: ts,  });

策略2

// Discountsroutings.fields is in /lib/Discountroutings.js
Discountsroutings.fields = ['_id', 'created_td', 'updated_td', 'client_updated_td', 'name', 'discounts', 'locations', 'url_map'];

// this is in /server/discountsroutings.js var ts = new Date();
doc.created_td = ts; doc.updated_td = ts; return _.each(doc,function(value, key, list){  
  if(Discountsroutings.fields.indexOf(key)  == -1 ){
    delete doc[key];   
  } 
});

都没有奏效。在这两种情况下,虽然添加了字段,但未删除字段。

有趣的是,我在插入允许和插入拒绝中尝试了相同的两个策略,只有策略#2工作。所以,现在我只是在Deny插入/更新方法中使用策略#2 。工作正常,并没有那么难以接线。

我这样做是否正确?我想以正确的方式在集合服务器端添加或删除字段。

3 个答案:

答案 0 :(得分:2)

Steeve你有没有试过我的收藏钩包?听起来像你需要的

答案 1 :(得分:0)

您似乎知道要删除的字段列表。那么为什么不使用$set$unset来添加和删除字段?

答案 2 :(得分:0)

最近需要做同样的事情,在这里找不到任何例子......以为我分享了我是如何做到的:

使用

  • https://atmospherejs.com/matb33/collection-hooks
  • http://arasatasaygin.github.io/is.js/

    Prospects.before.update(function (userId, doc, fieldNames, modifier, options) {
    
    
    //check existence of other segment property and make sure to delete it if segment is updated from 'Other...' to something else
    if (is.existy(doc.other_segment)) {
        var segment = Segments.findOne({_id: modifier.$set.segment});
    
        if (is.not.undefined(segment) && is.not.empty(segment)) {
            if (is.not.equal(segment.name, 'Other...')) {
                Prospects.update( {_id: doc._id} , {$unset: { other_segment : '' } } );
            }
        }
    
    }});
    

希望这有帮助! :)

相关问题