I'm a hobbyist web programmer who just started learning MongoDB/Mongoose and I can't seem to figure out how to append to a string located in a deep nested array. I am trying to append a string to the end of hours: String. Below is the Schema I'm working with:
const TestSchema = new Schema({
userID: Number,
years: [
{
year: Number,
months: [{
month: Number,
days: [{
day: Number,
hours: String
}]
}]
}
]
});
Here is what I have so far. I tried to extend upon this answer here: https://stackoverflow.com/a/56589089 .But this is giving me a Cannot specify arrayFilters and a pipeline update error.
TestModel.findOneAndUpdate(
{ "years.months.days.day": 12 },
[
{
$set: {
"years.$[index1].months.$[index2].days.$[index3].hours": {
$concat: [
"$years.$[index1].months.$[index2].days.$[index3].hours",
" 44:44:44"
]
}
}
}
],
{
arrayFilters: [
{ "index1.year": 2020 },
{ "index2.month": 7 },
{ "index3.day": 12 }
]
}
).catch(error => {
console.log("error>>" + error);
});
Edit: Below is code with which I created an instance of the model
var test = new TestModel({
userID: 5,
years: [{
year: 2020,
months: [{
month: 7,
days: [{
day: 12,
hours: "4:4:4 5:5:5"
}]
}]
}]
})
test.save().then(function(){
console .log("testSaved>>" + !test.isNew);
});
Here is a screenshot of the data in the db:
Any help would be greatly appreciated.
$set? actually you can leave the condition blank{ "years.months.days.day": 12 }to this{}error>>CastError: Cast to string failed for value "{ '$concat': [ '$years.$[index1].months.$[index2].days.$[index3].hours', ' 44:44:44' ] }" at path "hours"$concat?hoursis aStringas you can see in the schema i posted. The value of hours in the single instance in db is"4:4:4 5:5:5"@Gibbs I was pretty much following the code in the post I referred to