簡體   English   中英

流星集合插入未在客戶端上更新

[英]Meteor collection insert not updating on client

我目前在Meteor中遇到收藏夾問題。 我調用了一種將新項目插入集合的方法。 服務器數據庫顯示新項目,但客戶端沒有集合的記錄。 我發現如果刷新頁面,引用集合的模板就會填充並起作用。

這是插入位於'lib / collections / items.js'的項目的方法

Items = new Mongo.Collection("items");

Meteor.methods({
  addItem: function (text) {
    if (! Meteor.userId()){
      throw new Meteor.Error("not-authorized");
    }
    console.log(text);
    console.log(Meteor.userId());
    console.log(Meteor.user().username);
    console.log(Meteor.user().household);
    Items.insert({
      text: text,
      createdAt: new Date(), //current time
      owner: Meteor.userId(),
      username: Meteor.user().username,
      household: Meteor.user().household
    });
  },

這是服務器發布的項目,位於“ /server/main.js”

Meteor.publish("items", function(){
  if(typeof Meteor.users.findOne({'_id': this.userId}) === 'undefined') return null;
    return Items.find( {household : Meteor.users.findOne({'_id': this.userId}).household});
}); 

這是調用位於“ client / main.js”中的方法的代碼

Template.body.events({
  "submit .new-task": function (event) {
    // This function is called when the new task form is submitted

    var text = event.target.text.value;
    text = text.trim();
    if(text)//Check for non-null, non-empty
      {
        text = capitalizeEachWord(text);
        console.log(text);
        Meteor.call("addItem",text);
      }

      //Clear form
      event.target.text.value = "";

      //Prevent default form submit
      return false;
    },

這是從中查詢集合的位置,以顯示在“ client / templates / itemList.js”中的模板中

Template.itemList.helpers({
  items: function() {
    console.log('Trying to subscribe');
    return Items.find({}, {sort : {checked: 1, createdAt: -1}});
  }

我才剛開始學習流星。 感謝您的幫助!

編輯

感謝您的回復,

我嘗試了這些建議,但仍得到相同的結果。 我嘗試了一種不同的方式來將用戶與家庭聯系起來,但仍然存在相同的問題。 我可以從客戶端插入一個項目,它存在於服務器端,但在客戶端不存在。 我確定我在這里想念一些小東西,但是我一生都找不到。

我知道這是大量的信息轉儲,但這是我更新的源代碼(仍然產生相同的問題)和日志。 我已經盡力將關於此問題的所有知識都投入了。 謝謝你的幫助! 我只是從Meteor入手,我不知道有誰在開發它,所以現在進行故障排除有點困難。

客戶特定代碼

位於“ client / main.js”

Template.body.helpers({
  householdId: function() {
    //return Meteor.users.findOne({'_id': Meteor.userId()}).household;
    if(Meteor.userId() &&
      Households.findOne({users : {$regex : new RegExp(Meteor.userId())}}))
    {      
      console.log('Trying to get id');
      return Households.findOne({users : {$regex : new RegExp(Meteor.userId())}})._id;
    }
  }
});
Template.body.events({
  "submit .new-task": function (event) {
    // This function is called when the new task form is submitted

    var text = event.target.text.value;
    text = text.trim();
    if(text)//Check for non-null, non-empty
      {
        text = capitalizeEachWord(text);
        console.log(text);
        Meteor.call("addItem",text);
      }

      //Clear form
      event.target.text.value = "";

      //Prevent default form submit
      return false;
    },
    "submit .new-household": function (event) {
      // This function is called when the new task form is submitted
      var insertedId;

      var text = event.target.householdName.value;
      text = text.trim();
      if(text)//Check for non-null, non-empty
        {
          text = capitalizeEachWord(text);
          Meteor.call("createHousehold", text);
        }


        //Prevent default form submit
        return false;
      }
  });


Accounts.ui.config({
  passwordSignupFields: "USERNAME_ONLY",
});

訂閱位於“ client / application.js”的我的收藏集的代碼

//Sub to our collections
Meteor.subscribe('households');
Meteor.subscribe('items');

代碼遍歷項目以顯示在“ client / templates / itemList.js”上

Template.itemList.helpers({
  items: function() {
    console.log('Trying to subscribe');
    return Items.find(
      {
        household : Households.findOne( {users : {$regex : new RegExp(this.userId)}})._id
      }
    , {sort : {checked: 1, createdAt: -1}});
  },
  householdId: function() {
    //return Meteor.users.findOne({'_id': Meteor.userId()}).household;
    if(Meteor.userId())
    {      
      console.log('Trying to get id from ');
      return Households.findOne({users : {$regex : new RegExp(Meteor.userId())}})._id;
    }
  }
});

托收代碼

位於“ lib / collections / households.js”的住戶收集代碼

Households = new Mongo.Collection("households");

Meteor.methods({
  createHousehold: function(text) {
    var insertedId;
    insertedId = Households.insert({
      householdName: text,
      createdAt: new Date(), //current time
      users: this.userId
    });
  }//Add user in the future
});

位於'lib / collections / items.js'的Items Collection代碼

Items = new Mongo.Collection("items");

Meteor.methods({
  addItem: function (text) {
    if (! Meteor.userId()){
      throw new Meteor.Error("not-authorized");
    }
    console.log('Inserting item')
    console.log('Item : ' + text);
    console.log('UserId : ' + Meteor.userId());
    console.log('Username : ' + Meteor.user().username);
    console.log('Household : ' + Households.findOne( {users : {$regex : new RegExp(Meteor.userId())}})._id);
    Items.insert({
      text: text,
      createdAt: new Date(), //current time
      owner: Meteor.userId(),
      username: Meteor.user().username,
      household: Households.findOne( {users : {$regex : new RegExp(Meteor.userId())}})._id
    });
    return true;
  },
  deleteItem: function (itemId) {
    Items.remove(itemId);
  },
  setChecked: function(itemId, setChecked) {
    Items.update(itemId, { $set: {checked: setChecked}});
  }
});

服務器代碼

服務器代碼位於“ server / main.js”

Meteor.publish("households", function(){
  console.log('Trying to subscribe');
  console.log(this.userId);
  if(this.userId)
  {
    //var query = { users : new RegExp("/"+this.userId+"/")};
    //console.log(Households.findOne( query ));
    console.log(Households.findOne( {users : {$regex : new RegExp(this.userId)}}));
    return Households.find( {users : {$regex : new RegExp(this.userId)}});
  }
  else
  {
    console.log('Too early');
    return null;
  }
});



Meteor.publish("items", function(){
  console.log('Trying to get items');
  if(!this.userId ||
    !Households.findOne( {users : {$regex : new RegExp(this.userId)}}))
    {
      console.log('Returning null');
      return null;
    }
    console.log(Items.findOne( {household : Households.findOne( {users : {$regex : new RegExp(this.userId)}}) }));
    console.log(this.userId);
    return Items.find( {household : Households.findOne( {users : {$regex : new RegExp(this.userId)}})._id });
  });

日志

如果我使用流星在localhost上啟動站點。 頁面出現時(沒有用戶登錄),服務器控制台輸出:

=> App running at: http://localhost:3000/
I20141209-10:26:50.719(-5)? Trying to subscribe
I20141209-10:26:50.766(-5)? null
I20141209-10:26:50.766(-5)? Too early
I20141209-10:26:50.766(-5)? Trying to get items
I20141209-10:26:50.767(-5)? Returning null

接下來,我成功創建了一個用戶帳戶(使用accounts-ui / accounts-password程序包)。 這是該點的輸出。

I20141209-10:31:59.562(-5)? Trying to subscribe
I20141209-10:31:59.565(-5)? null
I20141209-10:31:59.566(-5)? Too early
I20141209-10:31:59.566(-5)? Trying to get items
I20141209-10:31:59.566(-5)? Returning null
I20141209-10:32:16.145(-5)? Trying to subscribe
I20141209-10:32:16.145(-5)? 8Skhof4jL2pSguT8Q
I20141209-10:32:16.146(-5)? undefined
I20141209-10:32:16.147(-5)? Trying to get items
I20141209-10:32:16.148(-5)? Returning null

接下來,我使用.new-household表單創建一個家庭。 此時服務器上沒有新的輸出,但這是客戶端的輸出:

main.js?ba2ac06f3ff7f471a7fa97093ac9ed5c01e0c8cd:7 Trying to get id
main.js?ba2ac06f3ff7f471a7fa97093ac9ed5c01e0c8cd:7 Trying to get id
itemList.js?a224bda493b90eb94bff9b88b48bb22eaa8aefe1:3 Trying to subscribe
main.js?ba2ac06f3ff7f471a7fa97093ac9ed5c01e0c8cd:7 Trying to get id
main.js?ba2ac06f3ff7f471a7fa97093ac9ed5c01e0c8cd:7 Trying to get id
itemList.js?a224bda493b90eb94bff9b88b48bb22eaa8aefe1:3 Trying to subscribe

此時,我使用.new-task表單添加一個項目。 任務在屏幕上閃爍顯示,然后消失。 這是此時的服務器輸出:

I20141209-10:37:09.171(-5)? Inserting item
I20141209-10:37:09.172(-5)? Item : Beans
I20141209-10:37:09.172(-5)? UserId : 8Skhof4jL2pSguT8Q
I20141209-10:37:09.172(-5)? Username : pedro
I20141209-10:37:09.173(-5)? Household : M5NckT6ndqhRKCeWo

這是客戶端此時的輸出:

main.js?ba2ac06f3ff7f471a7fa97093ac9ed5c01e0c8cd:21 Beans
items.js?2ca606d1e71e2e55d91421d37f060bd5d8db98fe:8 Inserting item
items.js?2ca606d1e71e2e55d91421d37f060bd5d8db98fe:9 Item : Beans
items.js?2ca606d1e71e2e55d91421d37f060bd5d8db98fe:10 UserId : 8Skhof4jL2pSguT8Q
items.js?2ca606d1e71e2e55d91421d37f060bd5d8db98fe:11 Username : pedro
items.js?2ca606d1e71e2e55d91421d37f060bd5d8db98fe:12 Household : M5NckT6ndqhRKCeWo

此時,Item存在於服務器數據庫中,但是如果我使用chrome中的Web控制台,則執行命令Items.findOne();。 它返回未定義。

可能還有更多,但我看不到您在客戶端包含Meteor.subscribe("items")的位置,因為這是將記錄從服務器上的發布傳遞給客戶端的原因。

同樣在您的發布中,您可以使用

if (this.userId) {
    //do stuff logged in
} else {
    this.stop();
}

而不是選擇Meteor.user()記錄作為用戶ID來檢測客戶端是否已登錄。

您的出版物:

Meteor.publish("items", function(){
  if(user = Meteor.user()){
    return Items.find( {household : user.household});
  }
  else{
    this.ready();
  }
});

您的區塊幫手:

Template.itemList.helpers({
  items: function() {
    return Items.find({}, {sort : {checked: 1, createdAt: -1}});
  }
});

您的訂閱(客戶端):Meteor.subscribe(“ items”);

如果您使用的是iron:router。 在路由中,您可以像這樣直接定義您的助手和您的訂閱,只需在模板中調用{{items}}:

    Router.route('myRoute', function(){
        this.render('myRouteTemplate');
    }, {
    path: '/myRoutePath',
    waitOn: function(){
        if(user = Meteor.user()) {
            var subscriptions = [];
            //
            // Subscribe to your subscription
            //===============================
            subscriptions.push(Meteor.subscribe('items'));

            return subscriptions;
        }
    },
    data: function(){
        var context;
        if(this.ready()) {
            if (user = Meteor.user()) {
            context = {
                items: Items.find( {household : user.household})
              };
            }           
        }
    }
    });

始終記住,當您發行雜志時,需要一個訂閱者流程。 集合也一樣。

干杯,

我最終通過在應用程序中實現Iron Router並在呈現模板之前等待訂閱准備就緒來解決此問題。 我認為我以前的問題是某種比賽條件,但我對其具體情況並不滿意。 無論哪種方式,我都對我的解決方案感到滿意,因為它可以解決我的問題並更好,更容易理解我的網站結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM