Jef Vandooren
Jef Vandooren

Reputation: 124

sending array of data in object to API results in empty array in object

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.

Upvotes: 0

Views: 77

Answers (1)

adhi narayan
adhi narayan

Reputation: 320

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

try this one

Upvotes: 2

Related Questions