1

I'm trying to push values to an array at a specific index of an array using the following code:

Freezer.update(conditions, {$push: {shelves[shelfindex] : {"rackname": rackname, "columns": columns, "rows": rows, "spaces" : []}}}, function (err, doc){

          console.log(doc);
        })

where shelfindex is the index of the shelf at hand, that I find with a preceeding for loop (code not shown).

It's not working (the program won't even start up). I get the following error:

SyntaxError: Unexpected token [

My shelves array is set up like:

[{"racks":[],"shelfname":"Shelf 1"},{"racks":[],"shelfname":"Shelf 2"},{"racks":[],"shelfname":"Shelf 3"}]

So for instance if I was trying to push rack data to "Shelf 1" I am attempting to push it to:

shelves[0].racks

Any ideas for a solution?

1 Answer 1

2

Would have been a little bit helpful if you had shown your Freezer model schema. Nonetheless the following example is based on the sample data (example):

{
    "_id" : ObjectId("565236570f7f257d5feffa10"),
    "shelves" : [ 
        {
            "racks" : [],
            "shelfname" : "Shelf 1"
        }, 
        {
            "racks" : [],
            "shelfname" : "Shelf 2"
        }, 
        {
            "racks" : [],
            "shelfname" : "Shelf 3"
        }
    ]
}

So, pushing rack data to "Shelf 1" shelf in mongo shell would use the positional $ operator which only supports one level deep and only the first matching element in its update. Note, the shelves array field must appear as part of the query document, hence { "shelves.shelfname": "Shelf 1" }:

db.freezer.update(
    { "shelves.shelfname": "Shelf 1" },
    {
        "$push": {
            "shelves.$.racks": {
                "rackname": 1, 
                "columns": 3, 
                "rows": 2, 
                "spaces" : []       
            }
        }
    }
);

Now, if you knew the specific array index then create the update document using the bracket notation:

var update = { "$push": {} },
    condition = { };

condition["shelves.shelfname"] = "Shelf "+ shelfindex + 1;
update["$push"]["shelves."+ shelfindex +".racks" ] = {
    "rackname": rackname, 
    "columns": columns, 
    "rows": rows, 
    "spaces" : []
};

db.freezer.update(condition, update);

In your node.js, this would be similar but with a callback:

Freezer.update(conditions, update, function (err, doc){
    console.log(doc);
});
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.