Sukhmeet Singh
Sukhmeet Singh

Reputation: 130

Inserting data of type String in Array within object which is in another array

How can I insert data of type String in array within object which is in another array?

The below is my array:

productRequirements: [{
    question: "What type of Business Bag do you need?",
    type: "checkbox",
    specifications: [
        "Luggage Bag",
        "Handbag",
        "Shoulder Bag",
        "Soft Bag",
        "Laptop Bag",
        "Tote Bag",
        "Not Sure",
        "Others"]
}, {
    question: "What kind of logo do you prefer on your bag?",
    type: "radio",
    specifications: [
        "OEM",
        "Embossed",
        "Debossed",
        "Printed",
        "Customized",
        "Not Sure",
        "Others"]
}]

I want to insert strings in specifications one by one and I am trying the following code:

Products.update({
    _id: productId,
    "productSpecifications.Specification": listing["Specification"]
}, {
    $push: {
        "productSpecifications.$.Options": {
            Options: listing["Options"]
        }
    }
})

which is inserting object instead of string. How can I rectify it?

Upvotes: 1

Views: 64

Answers (1)

e_m0ney
e_m0ney

Reputation: 980

I think that the issue is an extra set of curly braces around Options:listing["Options"]. The current command is telling it to push an object to the options list.

Perhaps try this instead

Products.update({_id:productId,"productSpecifications.Specification":listing["Specification"]},
                    {$push: { "productSpecifications.$.Options": listing["Options"]
                }})

Also - if listing["Options"] is an array, $push will push the whole array as a single object, in which case you should use $each with $push:

{$push: {field: {$each: [value1, value2]}}}

Also - consider using $addToSet instead of $push where you want to maintain unique array elements. $addToSet also works with $each

{$addToSet: {field: {$each: [value1, value2]}}}

Hope this helps, be sure to let me know!

Upvotes: 2

Related Questions