3

I want to populate the ingredientsList. Is it possible to get the array back with populated ingredients field ? How I can do it, if I want just one object out of ingredientsList with populated ingredient ?

Hope you can help :)

My Schema looks like this:

export const RecipeSchema = new Schema({
  name: {
    type: String,
    required: 'Enter a name',
  },
  ingredientsList: [
    {
      ingredient: {
        type: Schema.Types.ObjectId,
        ref: 'Ingredient',
      },
      value: {
        type: Number,
        default: 1,
      },
    },
  ],
});

My Ingredient Model looks like this:

export const IngredientSchema = new Schema({
  name: {
    type: String,
    required: 'Enter a name',
  },

  created_date: {
    type: Date,
    default: Date.now,
  },
  amount: {
    type: Number,
    default: 1,
  },
});

1 Answer 1

3

As the field, ingredientsList, is an array of referenced documents from the Ingredient collection - you can use model.populate() as follows:

const recipes = await Recipe.find().populate('ingredientsList');

res.send({ data: orders });

This will return all Recipes and also expand or populate the ingredientsList for each.

Let's say that you only wanted populate the name field of each document in ingredientsList - you do so as follow:

const recipes = await Recipe.find().populate('ingredientsList', 'name');

res.send({ data: orders });

This will return all Recipes but only populate the name field on ingredientsList for each.

Mongoose docs on population

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.