1

我想在我的发布方法中修改 find() 光标中匹配的文档。但是,它不应该保存到 Mongo 中。

例子:

Email.find({}) 返回一个类似 {email: "hello@hello.com"} 的文档,它匹配 Mongo 集合中的记录。

但我想做一个额外的步骤,即检查电子邮件是否经过验证(可能在另一个集合中,或者一些逻辑程序中,并像这样附加它。

也就是说,我想发布

{ 电子邮件:“hello@hello.com”,is_verified:真 }

Mongo 中的文档仍然是 {email: "hello@hello.com"}

我怎样才能做到这一点?谢谢!

4

2 回答 2

1
var Docs = new Meteor.Collection('docs', {

     transform: function(doc) {

         ...
         return anythingYouWant;
     },

});

或者

var docs = Docs.find({...}, {

     transform: function(doc) {

         ...
         return anythingYouWant;
     },

});

请参阅http://docs.meteor.com/#meteor_collectionhttp://docs.meteor.com/#find

于 2013-07-13T17:48:53.223 回答
1

Meteor docs中所述,如果您仔细阅读, transform这不是问题的正确解决方案:

文档将在从fetch 或 findOne返回之前通过此函数传递,在传递给 observe、map、forEach、allow 和 deny 的回调之前。转换不适用于observeChanges 的回调或发布函数返回的游标

在出版物中转换文档的正确解决方案是使用像maximum:server-transform这样的包:

$ meteor add maximum:server-transform
Meteor.publishTransformed('allDocsTransformed', function() {
  return Docs.find().serverTransform({
    extraField: function(doc) {
      // use fields from doc if you need to
      return 'whatever';
    }
  });
});

...或通过编写自定义出版物来DIY,您可以在其中与观察者一起处理文档流,如下所示:

function transform(doc) {
  doc.extraField = 'whatever';
  return doc;
}

Meteor.publish('allDocsTransformed', function() {
  const observer = Docs.find({}).observe({
    added: (doc) => {
      this.added('collectionName', doc._id, transform(doc));
    },
    changed: (doc) => {
      this.changed('collectionName', doc._id, transform(doc));
    },
    removed: (doc) => {
      this.removed('collectionName', doc._id);
    }
  });

  this.onStop(() => observer.stop());
  this.ready();
});

无论哪种方式都有效。

于 2019-07-14T19:16:18.980 回答