Creare new collecuon for each user meteor
In Meteor, you can create a new collection for each user by using a combination of the Meteor.users
collection and a separate collection for the user's data.
Here's an example of how you can do this:
- First, create a new collection for the user's data:
// collections.js import { Mongo } from 'meteor/mongo';
const UserCollection = new Mongo.Collection('user_data');
export default UserCollection;
2. Then, in your server code, you can create a new instance of the `UserCollection` for each user:
// server.js import { Meteor } from 'meteor/meteor'; import { UserCollection } from './collections';
Meteor.publish('userData', function () { const userId = this.userId; if (userId) { const userCollection = new UserCollection(userId); return userCollection.find(); } else { return []; } });
In this example, the `Meteor.publish` function creates a new instance of the `UserCollection` for each user, using the `userId` as the name of the collection. The `find` method is then used to retrieve the user's data from the collection.
3. On the client side, you can subscribe to the `userData` publication and access the user's data using the `UserCollection` instance:
// client.js import { Meteor } from 'meteor/meteor'; import { UserCollection } from './collections';
Meteor.subscribe('userData');
Template.myTemplate.helpers({ userData() { const userCollection = UserCollection.get(Meteor.userId()); return userCollection.find().fetch(); } });
In this example, the `Meteor.subscribe` function subscribes to the `userData` publication, and the `UserCollection` instance is used to retrieve the user's data.
Note that this approach requires you to create a new collection for each user, which can be inefficient if you have a large number of users. An alternative approach is to use a single collection for all user data, and use a field in the collection to identify the user. For example:
// collections.js import { Mongo } from 'meteor/mongo';
const UserCollection = new Mongo.Collection('user_data');
export default UserCollection;
// server.js import { Meteor } from 'meteor/meteor'; import { UserCollection } from './collections';
Meteor.publish('userData', function () { const userId = this.userId; if (userId) { return UserCollection.find({ userId: userId }); } else { return []; } });
// client.js import { Meteor } from 'meteor/meteor'; import { UserCollection } from './collections';
Meteor.subscribe('userData');
Template.myTemplate.helpers({ userData() { return UserCollection.find({ userId: Meteor.userId() }).fetch(); } });
In this example, the `UserCollection` is used to store all user data, and a `userId` field is used to identify the user. The `Meteor.publish` function returns a cursor that only includes documents with the specified `userId`, and the `Meteor.subscribe` function subscribes to the publication. The `UserCollection` instance is then used to retrieve the user's data on the client side.