So I have a model which contains this as part of it. I'm trying to insert records that are categorized by day("7/20/2017", "7/21/2017"), and then individually time stamped.
My issue is how do you upsert in Mongoose to not only push the record, but create the parent/observation if needed
observations : [
{
date : {type: Date, default: new Date().toLocaleString().split(',')[0]},
record :
[
{
category : String,
timestamp : {type: Date, default: Date.now()},
}
]
}
],
Here's my current update code for pushing records on the current day, but I'm not sure how to get the nested upsert to work when the observation with "date" doesn't exist:
var todayISO = "7/21/2017"
var observation = {
"category": "Diaper",
"timestamp": todayISO,
}
Child.findOneAndUpdate({"child.firstName.name": studentName, "child.observations.date": todayISO} , {$push: {"child.observations.$.record": observation}}, {upsert: true, new: true}, function(err,result){
if(err){
console.log("error");
return res.status(500).json({err: "Couldn't append record"});
}
else {
console.log("added");
return res.json({'record': observation, message: 'Added record under ' + observation.category});
}
});
So that this:
"observations":
[
{
date: "2017-07-20T04:00:00.000Z",
"record":
[
{"category":"Diaper",timestamp: "2017-07-06T21:04:30.337Z"}
]
}
Becomes this when a user tries to log a record on a new day:
"observations":
[
{
date: "2017-07-20T04:00:00.000Z",
"record":
[
{"category":"Diaper",timestamp: "2017-07-20T21:04:30.337Z"}
]
},
{
date: "2017-07-21T04:00:00.000Z",
"record":
[
{"category":"Nap",timestamp: "2017-07-21T10:04:30.337Z"}
]
}
]