【问题标题】:Meteor subscribe to collection returns zero documentsMeteor 订阅集合返回零文档
【发布时间】:2021-07-18 17:11:40
【问题描述】:

当客户端代码中的console.log 时,此 Meteor 代码未能返回 Vehicles 集合中的文档数。请帮助找出我出错的问题。谢谢

//imports/api/vehicles.js
import {Mongo} from 'meteor/mongo';
export const Vehicles = new Mongo.Collection('vehicles');
///////////////////////////////////////////

//server/publish.js
import {Vehicles}   from '../imports/api/vehicles.js'

Meteor.publish('vehicles', function(){
    return Vehicles.find({})
})
///////////////////////////////////////////

//server/main.js
import { Vehicles } from '../imports/api/vehicles.js';

//so I added this tying to fix the problem for no avail
Meteor.startup(() => {
  Meteor.publish('vehicles', function () { 
    return Vehicles.find();
  });
});
///////////////////////////////////////////

//client/main.js
import {Vehicles} from '../imports/api/vehicles.js'
Meteor.startup(function(){
  Meteor.subscribe('vehicles');
  console.log('subscribed') //<<<<<< prints "subscribed"
  
  let rec = Vehicles.find({}).count()
  console.log(rec) //<<<<<< prints "0"
})
///////////////////////////////////////////

Blaze 集合 findOne 不返回任何文档 阅读第一个回复后,关于 Blaze 会自动执行,而我不必这样做 Meteor.startup Meteor.subscribe.onReady... 请注意下面的 blaze 模板助手给出了 undefined。

//client/main.js
Tracker.autorun(() => {
  Meteor.subscribe('vehicles', {plate: Session.get('plate')});
});

Template.vehicle.helpers({
  'vehicle' : function(){
    let vehicle = Vehicles.findOne({'plate':Session.get('plate')})
    console.log(vehicle) //prints undefined
  }
})

Template.vehicle.events({ 
  'keyup #plate'(e, inst){
      let str = e.currentTarget.value
        Session.set('plate', str)
        console.log(str) // prints the value OK
  }
})

【问题讨论】:

  • Meteor.subscribe 的 onError 键被触发,其参数打印在浏览器控制台中,显示“未找到订阅‘车辆’[404]”。但它存在于单独的提示符meteor mongo> 显示集合> 车辆

标签: node.js meteor


【解决方案1】:

订阅不会立即准备就绪。您需要先等待数据到达客户端。请记住,客户端上的所有内容都是异步的,因为浏览器中没有 Fiber(与服务器上不同)。这就是为什么 subscribe 函数有一个可以指定的 onReady 回调:

Meteor.startup(function(){
  Meteor.subscribe('vehicles', {onReady: () => {
    console.log('subscription ready') 
    let rec = Vehicles.find({}).count()
    console.log(rec)
  }});

  console.log('subscribed') // << this will print first
})

实际上,您不需要这样做,因为您通常会在 UI 组件中使用集合中的数据,并且 UI 框架(例如,Blaze 或 React)将负责一次响应式重新渲染数据到了。在完全自动的 Blaze 中,在 React 中您需要使用 useTrackerwithTracker。无论哪种方式,您正在运行的测试仍然有助于加深对 Meteor 的理解。

如果您想了解更多信息,请在浏览器中打开开发者控制台,转到网络,然后查看 WS(网络套接字)上的消息。您将学到很多关于 DDP 的工作原理,Meteor 用于在服务器和客户端之间同步数据的协议。即使只是了解 DDP 的基础知识,也能真正帮助您构建更好的 Meteor 应用程序并对其更有信心。

【讨论】:

  • 谢谢,请阅读我发布的更新,即使集合中的文档存在,火焰助手也找不到。
  • 我认为您的更新最好作为一个新问题发布。
猜你喜欢
  • 2015-11-29
  • 2015-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 2015-04-21
相关资源
最近更新 更多