cdimascio / uuid-mongodb

📇 Generates and parses MongoDB BSON UUIDs
MIT License
101 stars 17 forks source link

How do I populate an array field? #50

Closed IsraelGboluwaga closed 3 years ago

IsraelGboluwaga commented 3 years ago

Hello.

So there are not examples of how I can populate an array field from a different schema. For example;

Country Model;

const CountrySchema = new Schema(
  {
    _id: {
      type: "object",
      value: { type: "Buffer" },
      default: () => MUUID.v4(),
    },
    name: {
      type: String,
      unique: true,
      required: true,
    },
  }
 )

Festival Model;

const FestivalSchema = new Schema(
  {
    _id: {
      type: "object",
      value: { type: "Buffer" },
      default: () => MUUID.v4(),
    },
    name: {
      type: String,
      unique: true,
      required: true,
    },
    allowedCountries: [
      {
        type: Schema.Types.Mixed, // "object" does not work
        ref: config.mongodb.collections.cards.country,
        required: true,
      },
    ],
  }
)

"object" as a type does not work in the allowedCountries array. It gives the following error;

TypeError: Invalid schema configuration: `object` is not a valid type within the array `allowedCountries`.See http://bit.ly/mongoose-schematypes for a list of valid schema types.

I am able to save a festival with an array of UUIDs, but when fetching i can not seem to be able to populate because it always returns an empty array. Here is the command;

const brand = await FestivalModel
      .findOne({ _id: MUUID.from(festivalId) })
      .populate('allowedCountries', { id: 1, name: 1, slug: 1 })
      .exec();

I believe I'm getting something wrong in my approach. Please help.

IsraelGboluwaga commented 3 years ago

Fixed it. All I had to do was to apply MUUID.from to the content of the array I was passing into allowedCountries before saving.