import {favRestaurants} from '/lib/collections';
import {Meteor} from 'meteor/meteor';
import {check} from 'meteor/check';
export default function () {
Meteor.methods({
'favRestaurants.create' (id, name, rating, priceLevel, type) {
check(id, String);
check(name, String);
check(rating, Number);
check(priceLevel, Number);
check(type, String);
const createdAt = new Date();
const restaurant = {id, name, rating, priceLevel, type, createdAt};
if(check(Meteor.user()) == null){
console.log('onlye logged in users can data');
}else{
FavRestaurants.insert(restaurant);
}
}
});
}
这是我将数据添加到餐厅集合的插入方法。当我在控制台中记录“check(Meteor.user())”时,我得到 null 作为输出。按照这种逻辑,您不应该能够将数据添加到集合中,尽管这仍然是可能的。
我还想为每个用户制作个性化的 FavResaurants 系列。我尝试检查是否有用户,然后在客户端的 main.js 文件中添加一个集合。
Meteor.loggingIn(() => {
console.log('check for user method');
var restId = 0;
if(Meteor.user() != null){
console.log('created new collection for the user');
const FavRestaurants = new Mongo.Collection('favRestaurants' + restId);
}
restId++;
});
我在 meteor docs 中找到了使用此方法没有得到任何输出到控制台.是代码放错地方了吗?非常感谢任何帮助。
根据docs Accounts.ui.config 是我应该使用的方法。但我不确定我应该把它放在代码中。到目前为止,此方法的放置已导致我的应用程序崩溃。
最佳答案
回答你的第一个问题,只允许登录的客户端访问一个方法,你应该使用类似的东西:
if (!Meteor.userId()) {
throw new Meteor.Error('403', 'Forbidden');
}
现在,我看到您想要一个集合来存储客户端每个用户最喜欢的餐馆。但正如我所见,每个客户端只有一个登录用户,因此您不需要为每个用户单独收集一个集合(因为集合在每个客户端中),您只需使用它的 ID 来引用用户,然后通过如下查询获取用户最喜欢的餐厅:
FavRestaurants.find({user: Meteor.userId()});
此外,作为 docs建议,Meteor.loggingIn
是一种告诉您是否有用户正在登录的方法。您正在做的是覆盖它,这是没有意义的。
你应该这样做:
if (Meteor.loggingIn()) {
// Do your stuff
}
希望它能让你更清楚。
关于mongodb - 为登录用户创建个人收藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40564652/