1

I have another question about mongoose. This time I want to update array element inside other array in my document. It's strucuture looks like this

{
    "_id" : ObjectId("5702e0c732faf57c7bb9ebe9"),
    "email" : "[email protected]",
    "projects" : [ 
        {
            "name" : "inbox",
            "title" : "Inbox",
            "tasks" : [ 
                {
                    "id" : "1",
                    "text" : "First task",
                    "labels" : [ 
                        "home", 
                        "phone"
                    ],
                    "dueDate" : "2016-03-18T11:10:00",
                    "created" : "2016-03-10T10:10:00",
                    "completed" : false
                }
            ]
        }, 
        {
            "name" : "work",
            "title" : "Work",
            "tasks" : [ 
                {
                    "id" : "4",
                    "text" : "Fourth",
                    "labels" : [ 
                        "home", 
                        "phone"
                    ],
                    "dueDate" : "2016-03-18T11:10:00",
                    "created" : "2016-03-10T10:10:00",
                    "completed" : false
                }
            ]
        }
    ]
}

I want to find document by _id, select project by name and then add new task inside tasks array. What is the best way to do this? For now I tried to use findOne to see if I'm querying right place

User.findOne(
  { _id: Mongoose.Types.ObjectId(userId), 'projects.name': data.project },
  (err, data) => {
    if (err) { throw err; }

    console.log(data);
  }
);

But it returns all projects in array and I don't know how to select project I'm looking for and add element to tasks array.

2 Answers 2

3

Try this

User.update({_id:ObjectId(userId),'projects.name': data.project},{$push:{'projects.$.tasks':{yourTaskObject}}})

$ in update works as positional operator which fetches the position of the parent array

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

Comments

1

I found a solution

User.update(
  { _id: Mongoose.Types.ObjectId(userId), 'projects.name': data.project },
  { $push: { 'projects.$.tasks': data.task } },
  (err, data) => {
    if (err) { throw err; }

    return reply('success');
  }
);

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.