Home > database >  How do I restrict the db fields stored in a material-ui Autocomplete component in a React Meteor P
How do I restrict the db fields stored in a material-ui Autocomplete component in a React Meteor P

Time:12-24

I am building a Meteor application using React and material-ui.

I am restricting the fields returned to just the name (and _id) via the following code:

 const { heroNames } = useTracker(() => {
    const sub = Meteor.subscribe('heroes');

    return {
      heroNames: HeroesCollection.find({}, { name: 1 }, { sort: { name: 1 } }).fetch(),
      loading: !sub.ready(),
    };
  });

I then render my MUI Autocomplete component with the data returned in heroNames:

<Autocomplete multiple
              id="hero-selection"
              options={heroNames}
              disableCloseOnSelect
              getOptionLabel={(hero) => hero.name}
              isOptionEqualToValue={(option, value) => option._id === value._id}
              onChange={(e, value) => setWarbandHeroes(value)}
              renderOption={(props, hero, { selected }) => (
                        <li {...props}>
                          <Checkbox
                            icon={icon}
                            checkedIcon={checkedIcon}
                            style={{ marginRight: 8 }}
                            checked={selected}
                          />
                          {hero.name}
                        </li>
                      )}
              style={{ width: 500 }}
              renderInput={(params) => (
              <TextField {...params} label="Hero Selection" placeholder="Select Hero" />
                      )}
                    />

However, when I save the contents of the user's selections via the Autocomplete in the database, the entire Hero record is stored, not just the name and _id fields. I have been stumped on this for a while and would appreciate any help.

Ps - this is my first ever question posted on Stack Overflow. :)

CodePudding user response:

Meteor's API has a slightly different from Mongo if you want to restrict fields you need to use the field property

      heroNames: HeroesCollection.find({}, { fields: { name: 1 } }, { sort: { name: 1 } }).fetch(),
  • Related