Meteor:我应该如何更新用户 collection 以在 object / 字典中包含一个新属性?

Meteor: How should I update the Users collection to include a new attribute in the object / dictionary?

我试过从头到尾寻找答案,但似乎无法正常工作。我将 Meteor 与 Cordova 结合使用来构建移动应用程序。

我想为我的用户添加一个属性 collection(我登录时 Meteor 创建的那个)。 IE。例如,我想将 {currentHotel: "Something"} 添加到我的 db.Users collection.

我正在尝试以正确的发布 - 订阅方式执行此操作。使用 Meteor.methods 已被引用为不利于实时应用程序。无论哪种方式,我想了解如何使用发布 - 订阅更新用户 collection。

//On the server, I did
Meteor.publish("userData", function () {
    return Meteor.users.find({_id: this.userId},
       {fields:{services: 1, currentHotel: 1}});
});

因此客户端应该可以访问currentHotel 字段。现在更新 "currentHotel" 字段:

//On the client I do
Meteor.subscribe('userData');
var user = Meteor.users.findOne({"_id": Meteor.userId()});
Meteor.users.update({_id: user._id}, {$set:{currentHotel:'something'}});

//I tried this too
//Meteor.users.update({ _id: Meteor.userId() }, {$set: });

在浏览器控制台上我可以看到 "currentHotel" 和 "services" 很好,这意味着 publish-subscribe 有效。但是我似乎无法更新当前的酒店。我收到拒绝访问。这是为什么?

此外,如果 "currentHotel" 属性 在 Collection 中根本不存在,我如何使用类似的 publish-subscribe 添加它?我可以发布不存在的 属性 并允许客户订阅并添加 属性 吗?

我参考了 Meteor 文档,this, this and this,但似乎仍然无法正常工作! :-(

提前致谢!

您不应该更改用户对象的根字段:

Meteor.users.update(user, {$set: {"profile.currentHotel": "something"}});

在此处阅读更多内容:http://docs.meteor.com/#/full/meteor_users

编辑:如最新文档所示,此答案已变得无关紧要:https://guide.meteor.com/accounts.html#dont-use-profile

这个答案已经超过 1 年了 :) 事实证明,强制在 'profile' 字段下写入用户特定的字段作为一些严重的安全隐患(就像我一直认为的那样),因为它授予了权限给客户修改那些子字段。所以是的,你可以在根对象中设置字段,但要注意客户端不应修改的字段应该在没有写权限的字段下(否则属于同样的问题)。