【问题标题】:How to publish data without MongoDB through subscriptions in Meteor?如何通过 Meteor 中的订阅在没有 MongoDB 的情况下发布数据?
【发布时间】:2021-06-08 12:34:09
【问题描述】:

基本上,这就是我的想法:

客户

const Messages = new Mongo.Collection("messages");

Meteor.call("message", { room: "foo", message: "Hello world");
Meteor.subsribe("messages", "foo");

// elsewhere
const messages = Messages.find({ room: "foo" });

服务器

Meteor.methods({
  message: ({ room, message }) => {
    // 1. remove old messages in the room
    // 2. add new message to the room
  }
});

Meteor.publish("messages", function (room) {
   // 1. return message collection for room
});

我假设客户端使用minimongo,这很好,但服务器无权访问 MongoDB 实例。

服务器上的实现是什么?

【问题讨论】:

  • 这可以按照文档中复杂的publish 示例,手动调用this.added 等来完成。但是如果您尝试在没有mongo 连接的情况下启动它,流星不会抱怨吗?你是否已经以某种方式克服了这个问题?
  • @ChristianFritz 不,meteor 不会抱怨缺少 MongoDB。我不记得我到底做了什么,但一切都在本地部署得很好。
  • 你为MONGO_URL设置了什么?
  • @ChristianFritz 什么都没有。只有两个环境变量:PORTROOT_URL。自去年 11 月以来,该应用程序一直在生产中不间断地运行,没有任何抱怨(空日志)。我知道我做了一些准备该应用程序的工作,因此不需要 MongoDB,但我不记得是什么。从那时起,我一直在从事许多项目。关键是,我需要添加这个功能:)

标签: javascript meteor ddp


【解决方案1】:

正如cmets中提到的,我认为这可以使用the documentation中描述的手动发布方法来实现。这样的事情可能会奏效:

// Server:

const rooms = {};

Meteor.publish('manualMessages', function(roomId) {
  check(roomId, String);
  rooms[roomId] = this;
  this.ready();
});

Meteor.methods({
  message: ({ roomId, message }) => {
    // 1. remove old messages in the room
    const room = rooms[roomId];
    if (!room) {
      throw new Meteor.Error('no room', 'that room does not exist');
    }
    room.removed('messages', roomId);
    // 2. add new message to the room
    room.added('messages', roomId, { message });
  }
});



// Client:
const Messages = new Mongo.Collection("messages");

Meteor.call("message", { room: "foo", message: "Hello world");
Meteor.subsribe("manualMessages", "foo");

// elsewhere
const messages = Messages.find({ room: "foo" });

要验证的一件事是publish 函数中的this 是否每个客户端都发生变化,在这种情况下rooms 应该包含数组,或者它是否是所有客户端的同一个对象,如此处假设。但希望这能为您指明正确的方向。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多