I got a data like this in my User collection on my MongoDB database
{
"_id" : ObjectId("5890a9598c36d45435d521c7"),
"name" : "Test Testsson",
"email": "test@test.com,"
"tasks": [{
"_id" : ObjectId("5890a9598c36d45435d521ce"),
"sessionid" : 0,
"value" : 7,
"actions" : [
{
"taskid" : 17,
"time" : 0.85302734375,
"_id" : ObjectId("5890a9598c36d45435d521d6")
},
{
"taskid" : 5,
"time" : 1.39321899414063,
"_id" : ObjectId("5890a9598c36d45435d521d5")
}
]
}, {
"_id" : ObjectId("5890a9598c36d45435d521qw"),
"sessionid" : 1,
"value" : 7,
"actions" : [
{
"taskid" : 1,
"time" : 0.85302734375,
"_id" : ObjectId("5890a9598c36d45435d521zx")
},
{
"taskid" : 5,
"time" : 1.39321899414063,
"_id" : ObjectId("5890a9598c36d45435d521yt")
}
]
}
]
}
I post data to my node / mongoose application and I want to update the tasks array.
I do a POST to /api/user/task/5890a9598c36d45435d521c7 with Body:
{
"sessionid" : 2,
"value" : 12,
"actions" : [
{
"taskid" : 4,
"time" : 0.85302734375,
"_id" : ObjectId("5890a9598c36d45435d521zx")
},
{
"taskid" : 9,
"time" : 1.39321899414063,
"_id" : ObjectId("5890a9598c36d45435d521yt")
}
]
}
I can find my tasks with this query:
User.findOne({
_id: ObjectId('58909be40c50e2d0345e916e'),
"tasks.sessionid": 0},
function(...){/* blah blah */});
But how do I update the data in the tasks array?
- If the sessionid exists I want to update the subdocument with the request body (given that the User exists)
- If the sessionid DONT exist I want to create a new object from the request body in the tasks array (given that the User exists)
- If the ObjectId of the User in the url parameter DONT exist send http status: 500
I tried with update and findAndModify but cant get it to work as expected. Anyone got any idees how to do this.