简体   繁体   中英

Meteor: How to add Username from Users collection to a new collection I created?

Quick question. How do I add a new field to a collection? For example, I have a collection named Teams and I want to add a Members field to it. Right now Teams only takes text (the team I create and add to the collection) and a createdAt date. My goal is to be able to find a user through my Users collection and add them as a member to the Team collection.

I'm not even sure where to start. I'm using the accounts-password package, btw. Right now this is what I have:

Template.teams.events({
   'submit .new-team'(event) {
      event.preventDefault()
      const target = event.target
      const text = target.text.value
      const members = target.members.value 
      newTeam.insert({
         text,
         createdAt: new Date(),
         members
      })
      (target.text.value = '')
   }
})

but I keep getting this error on my console: “TypeError: Cannot read property 'value' of undefined at Object.submit .new-team”

Any ideas on how to go about doing this? Would really appreciate the help. Thanks!

I am not familiar with meteor-blaze so I won't provide any useful code on front-end side but general idea is to:

1) Get Teams collection (same way you can get your Users)

2) Find team you're interested in using it's id and add new object property members (if doesn't exist)

3) update team with new memberId

I'm not sure what is your db structure, but let's say it looks similar to this:

{
  _id: teamId,
  name: teamName,
  createdAt: creationDate
}

Quick preview:

updateTeam(teamId, userId) => {
  const teams = Teams.find().fetch();
  let chosenTeam = teams ? teams.find(team => team._id === teamId) : {};

  if (chosenTeam && chosenTeam._id) {
     let members = chosenTeam['members'] || [];
     members.push(userId);

     Teams.update({_id: teamId}, {$set: {members}});
  }
}

Hope it helps

EDIT: Of course, before fetching Teams collection you need to provide publication on server side & subscribe it on client. Docs are really helpful in understanding this mechanism

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM