并且不确定在文档中的哪个位置可以找到它。如何向用户对象添加更多对象?
例如,如果我运行
meteor add accounts
我得到了一个完整的用户集合,其中包含一个有效的用户登录/注册模板。我想在此用户集合中添加一个帖子集合/对象,以便用户只能查看自己的帖子。
那么如何将每个帖子添加到当前用户对象中呢?
您可以通过添加包将用户添加到 Meteor.users 集合accounts-password
。使用Accounts.createUser()
方法创建新用户。
在此处查找文档:https://docs.meteor.com/api/passwords.html#Accounts-createUser
Meteor.users 是 Meteor 中用户集合的句柄。您可以像使用任何其他集合一样使用它 AKA
Meteor.users.findOne(id)
or
Meteor.users.update(...)
当然,您不能将帖子集合添加到用户集合中。这些将是不同的集合。
在用户集合文档下的MongoDB中存储对象非常简单:
Meteor.users.update(
{ _id: userId },
{ $set: { objectFieldName: { a: 1, b: 2 }}}
)
或者,如果您需要在用户创建时执行此操作,则应使用用户帐户包钩子。
你走错了。使用发布/订阅来实现此目的。
插入帖子时,请有一个名为 userId 或 ownerId 的字段
//inside Meteor.methods() on server side
Posts.insert({
owner: Meteor.userId(),
//some other fields
});
然后在您的出版物中,仅返回用户拥有的帖子
//publication on server side
//checks if the visitor is a user
//if user, returns that user's posts
Meteor.publish('posts', function() {
if (this.userId) {
return Posts.find({owner: this.userId})
}
});
然后订阅该出版物。无需参数:
//client side
Meteor.subscribe('posts')