3

コレクションと追加の値を返すことができる関数をサーバースクリプトで作成したいと思います。例えば:

Meteor.publish("users", function () {
    var users;
    users = Meteor.users.find();
    users.forEach(function (user){
        user.profile.image = "some-url";
    });
    return users;
});

しかし、これは適切に機能しません。私の質問は次のとおりです。公開関数でコレクション応答に値を追加する正しい方法は何ですか。

4

2 に答える 2

3

パブリッシュ機能を実装するには、次の 2 つの方法があります。

  1. カーソル (またはカーソルの配列) を返すことによって
  2. this.added()、this.changed()、this.removed() を使用する。

返されたドキュメントを変更できるのは、方法 2 のみです。

こちらの Meteor のドキュメントを参照してください。ただし、提供されているサンプル コードは複雑に見える可能性があるため、別のコードを次に示します。

// server: publish the rooms collection
Meteor.publish("rooms", function () {
  return Rooms.find({});
});

次と同等です。

// server: publish the rooms collection
Meteor.publish("rooms", function () {
  var self = this;
  var handle = Rooms.find({}).observeChanges({
    added:   function(id, fields) { self.added("rooms", id, fields); },
    changed: function(id, fields) { self.changed("rooms", id, fields); },
    removed: function(id)         { self.added("rooms", id); },
    }
  });
  self.ready();
  self.onStop(function () { handle.stop(); });
});

2 番目のサンプルでは、​​次のように、公開用に送信する前に「field」パラメーターを変更できます。

added: function(id, fields) { 
    fields.newField = 12;
    self.added("rooms", id, fields); 
},

出典:この投稿.

于 2015-02-08T09:18:46.553 に答える
2

これはサーバーとの関係で重要ですか? クライアントで変換機能を使用できます。

クライアント JS

//Somewhere where it can run before anything else (make sure you have access to the other bits of the document i.e services.facebook.id otherwise you'll get a services is undefined 

Meteor.users._transform = function(doc) {
    doc.profile.image = "http://graph.facebook.com/" + doc.services.facebook.id + "/picture";
    return doc;
}

今あなたがするとき:

Meteor.user().profile.image
=> "http://graph.facebook.com/55592/picture"

クライアントへの変換の共有に関して、以前に問題を開いたことがあります: https://github.com/meteor/meteor/issues/821

于 2013-03-23T05:34:53.753 に答える