在 Meteor.publish 中转换数据库集合
Transforming DB Collections in Meteor.publish
希望这个问题不会太长,但我正在尝试在我所做的事情中包含尽可能多的细节。
我想弄清楚如何在 Meteor.publish()
中实现从数据库中获取数据、更改列中的所有值并使更新后的集合可用于客户端订阅的逻辑。
具体来说,我有一个 table 存储用户之间的消息,收件人由他的 userId 标识。我想用他的实际 phone 号码替换 userId,该号码应该在 Meteor.users
table 中可用。
当我在网上查找它时,我看到了使用 transform
的建议,但我的理解是它不是反应性的。然后我了解了 map
但发现它 returns破坏 Meteor.publish()
方法的数组。最后我找到了一些使用 forEach
和 self.added()
和 self.ready()
的东西,所以我的代码目前看起来像这样:
Meteor.publish("myMessages", function () {
var self = this;
Messages.find({
$or: [
{ senderId: this.userId },
{ recipientId: this.userId }
]
}).forEach(function(m) {
m.recipientId = Meteor.users.findOne({ _id: m.recipientId }).username;
console.log("adding msg to collection:");
console.log(m);
self.added("Messages", m._id, m);
});
self.ready();
});
日志消息看起来正确,当 Meteor 重新启动时,它会打印与用户相关的数据库中的所有消息,其中收件人被正确替换为 phone 号码。但是,在客户端,当我尝试 运行 Messages.findOne(msgId)
(我通过直接在 mongo shell 中选择它来验证存在的 ID)我得到 undefined
回来,此外,运行ning Messages.find()
通过浏览器中的开发人员工具 returns undefined
以及尽管我希望日志中显示的消息可用..
我觉得这是一个基本用例,但我无法完成这项工作..感谢任何帮助!
"You can transform a collection on the server side like this:"
对我有用。
遗憾的是,用户集合中的更改不会反应性地更新这些自定义字段。
希望这个问题不会太长,但我正在尝试在我所做的事情中包含尽可能多的细节。
我想弄清楚如何在 Meteor.publish()
中实现从数据库中获取数据、更改列中的所有值并使更新后的集合可用于客户端订阅的逻辑。
具体来说,我有一个 table 存储用户之间的消息,收件人由他的 userId 标识。我想用他的实际 phone 号码替换 userId,该号码应该在 Meteor.users
table 中可用。
当我在网上查找它时,我看到了使用 transform
的建议,但我的理解是它不是反应性的。然后我了解了 map
但发现它 returns破坏 Meteor.publish()
方法的数组。最后我找到了一些使用 forEach
和 self.added()
和 self.ready()
的东西,所以我的代码目前看起来像这样:
Meteor.publish("myMessages", function () {
var self = this;
Messages.find({
$or: [
{ senderId: this.userId },
{ recipientId: this.userId }
]
}).forEach(function(m) {
m.recipientId = Meteor.users.findOne({ _id: m.recipientId }).username;
console.log("adding msg to collection:");
console.log(m);
self.added("Messages", m._id, m);
});
self.ready();
});
日志消息看起来正确,当 Meteor 重新启动时,它会打印与用户相关的数据库中的所有消息,其中收件人被正确替换为 phone 号码。但是,在客户端,当我尝试 运行 Messages.findOne(msgId)
(我通过直接在 mongo shell 中选择它来验证存在的 ID)我得到 undefined
回来,此外,运行ning Messages.find()
通过浏览器中的开发人员工具 returns undefined
以及尽管我希望日志中显示的消息可用..
我觉得这是一个基本用例,但我无法完成这项工作..感谢任何帮助!
"You can transform a collection on the server side like this:"
对我有用。
遗憾的是,用户集合中的更改不会反应性地更新这些自定义字段。