Mongodb 为登录用户创建个人收藏
这是我的insert方法,用于向餐厅集合添加数据。当我在控制台中记录“check(Meteor.user())”时,输出为null。按照这种逻辑,您不应该能够向集合添加数据,尽管这仍然是可能的 我还想为每个用户提供个性化的FavResaurants集合。Iv'e尝试检查是否有用户,然后在客户端的main.js文件中添加一个集合Mongodb 为登录用户创建个人收藏,mongodb,reactjs,meteor,Mongodb,Reactjs,Meteor,这是我的insert方法,用于向餐厅集合添加数据。当我在控制台中记录“check(Meteor.user())”时,输出为null。按照这种逻辑,您不应该能够向集合添加数据,尽管这仍然是可能的 我还想为每个用户提供个性化的FavResaurants集合。Iv'e尝试检查是否有用户,然后在客户端的main.js文件中添加一个集合 import {favRestaurants} from '/lib/collections'; import {Meteor} from 'meteor/meteor'
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);
}
}
});
}
我没有得到任何输出控制台使用这种方法,我发现在流星。代码放错地方了吗?任何帮助都是非常感激的
根据说明,Accounts.ui.config是我应该使用的方法。但我不确定我应该把它写在代码里。到目前为止,此方法的放置已导致我的应用程序崩溃 为每个用户创建集合是一种糟糕的方法。 定义您的favRestaurants集合一次,并在插入之前在餐厅文档中添加所有者字段。 创建一个发布方法,仅向客户端发布用户ID favrestaurant 还有一件事,在Meteor方法中首先检查您的用户ID,这将避免不必要的过程
Regs回答您的第一个问题,若要仅允许登录的客户端访问某个方法,您应该使用以下方法:
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++;
});
FavRestaurants.find({user: Meteor.userId()});
现在,我看到您需要一个集合来存储客户端中每个用户最喜欢的餐厅。但在我看来,每个客户端只有一个登录用户,因此您不需要每个用户都有一个单独的集合(因为集合在每个客户端中),您只需使用id引用用户,然后通过如下查询获取用户最喜欢的餐厅:
if (!Meteor.userId()) {
throw new Meteor.Error('403', 'Forbidden');
}
此外,正如建议的那样,Meteor.loggingIn
是一种告诉您是否有用户正在登录的方法。你所做的是过度驾驶,这是没有意义的
你应该这样做:
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++;
});
FavRestaurants.find({user: Meteor.userId()});
希望它能让您更清楚。需要在客户端和服务器端定义集合,但本地集合除外,本地集合仅在客户端定义,从未映射回服务器。集合在客户端和服务器端都定义