I originally created a string refillNote that I recently decided to convert to an array of objects refillNotes (see below). So I need to copy the string value of every User's refillNote string (from the refills array of objects) into the new object.
Due to both items being nested in different layers, I am not able to take the string data and inject it into the nested object using the $set method.
Here is the User object:
{
name:"Joe",
refills: [
{
refillNote: "original refill note",
refillNotes: [
{
note:"I need to copy the original refillNote here",
username:"Tim"
}
]
}
]
}
I simply want to take the existing refillNote string value from the refills array and create a new refillNotes object and inject it into the array as seen above.
Here is the current code I am using to add the new objects to the refillNotes array, but the issue is, I am not able to take the refillNote value and set it here:
User.updateMany(
{},
{
$set: {
"refills.$.refillNotes": [
{ username: "Joe", note: "refills.$.refillNote" }
]
}
}
);
This currently adds the note as the literal string "refills.$.refillNote" so I am stuck as to where in this sequence I would be able to extract the original refillNote value and be able to use it again in this $set method. Any input would be greatly appreciated.
Edit
Ending up using a hacky older forEach solution (below), which I was avoiding, but if anyone ever comes across this post with the aggregator based mongodb solution (or lack thereof), it would be awesome.
User.find({})
.then(function(results) {
return results.map(function(user) {
user.refills.forEach(function(refill) {
if (refill.refillNote) {
refill.refillNotes = [
{ username: "Tim", note: refill.refillNote }
];
} else {
refill.refillNotes = [];
}
});
return user.save();
});
})