0

I have an API to create cocktails. Each cocktail has a list of Ingredients. In the cocktailschema I want to add this as following (ingredients)

cocktailschema

const schema = new Schema({
    name: { type: String, required: true },
    recipe: {type: String, required: true },
    ingredients: [{
        ingredient: {type: mongoose.Schema.Types.ObjectId, ref: 'Ingredient'}
        quantity: {type: Number, required: false},
        quantityType: {type: String, required: false}
    }],
    creator: {
        type: mongoose.Schema.Types.ObjectId,
        ref:'User'
    },
    createdDate: { type: Date, default: Date.now }
});

I populate the cocktails as follows

return await Cocktail.find()
    .populate('ingredients', 'name alcoholic')
    .populate('creator', 'username')
    .select('name recipe ingredients creator');

When creating a Cocktail I give this as the body of my request. I use Postman to do this.

{
    "name": "Cooled Vodka",
    "recipe": "Vodka and Ice, what's there to do wrong?",
    "ingredients": [
        {
            "ingredient": "5eb8611ebf0d4b0017bf0d47",
            "quantity": "4",
            "quantityType": "pcs"
        },
        {
            "ingredient": "5eb86186bf0d4b0017bf0d48",
            "quantity": "4",
            "quantityType": "cl"
        }
    ],
    "creator": "5eb85eb0bf0d4b0017bf0d46"
}

where the two ingredient and the creator tags are valid IDs for respectively ingredients and a user. Sending the request gives a 200 OK status however when getting all the cocktails out of my db, this is the result. An empty array for the ingredients field

[
    {
        "_id": "5eb863b4bf0d4b0017bf0d4b",
        "name": "Cooled Vodka",
        "recipe": "Vodka and Ice, what's there to do wrong?",
        "ingredients": [],
        "creator": {
            "_id": "5eb85eb0bf0d4b0017bf0d46",
            "username": "Bartender",
            "id": "5eb85eb0bf0d4b0017bf0d46"
        },
        "id": "5eb863b4bf0d4b0017bf0d4b"
    }
]

I have no idea where I go wrong.

1 Answer 1

2
return await Cocktail.find()
    .populate('ingredients.ingredient', 'name alcoholic')
    .populate('creator', 'username')
    .select('name recipe ingredients creator');

try this one

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

2 Comments

Thanks! That worked. A simple solution but I couldn't find it by myself
No problem bro..!

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.