UPDATE: I adjusted the query using arrayFilters that someone here recommened, the query comes back as success, however values are never changed in the db.
I am trying to update certain fields within a mongodb collection according the the values passed to the database function.
module.exports.update_sprint = async function
update_sprint(teamname, update_data, sprint, sprintStar) {
for(var i in update_data) {
console.log(update_data[i].stars)
console.log(update_data[i].name)
TeamM.findOneAndUpdate({teamName: teamname}, {
$set: {
'sprints.$[a].stars.$[b].stars': update_data[i].stars,
'sprints.$[a].stars.$[b].points': update_data[i].points,
'sprints.$[a].sprintstars': sprintStar
}
}, {arrayFilters: [{"a.sprintnum": sprint}, {"b.name":
update_data[i].name}]}
,
function(error, success) {
if (error) {
console.log(error)
} else {
console.log(success)
}}
)
}
}
Database format: enter image description here
I am getting:
1
member1@lewisu.edu
0
member2@lewisu.edu
{
_id: new ObjectId("61b90840654b60a745e7e102"),
teamName: 'testing',
members: [ 'member1@lewisu.edu', 'member2@lewisu.edu' ],
scrumMaster: 'member1@lewisu.edu',
totalMembers: 2,
sprints: [ { sprintnum: 1, stars: [Array], sprintstar: 'None' } ],
__v: 0
}
{
_id: new ObjectId("61b90840654b60a745e7e102"),
teamName: 'testing',
members: [ 'member1@lewisu.edu', 'member2@lewisu.edu' ],
scrumMaster: 'member1@lewisu.edu',
totalMembers: 2,
sprints: [ { sprintnum: 1, stars: [Array], sprintstar: 'None' } ],
__v: 0
}
The query is coming back as success, however values are not updated in the database
In your request u want to match sprints = sprintum, you just have to change it to this:
Test.updateOne({ teamName: "test123", "sprints.sprintnum": 1 }, { // Mistake was in this line
$set: {
'sprints.$.stars': update_data,
'sprints.$.sprintstar': sprintStar
}
})
Before:
{
"teamName": "test123",
"members": [
"test@lewisu.edu",
"test@lewisu.edu"
],
"scrumMaster": "test@lewisu.edu",
"totalMembers": 2,
"sprints": [
{
"sprintum": 1,
"stars": [
{
"name": "test@lewisu.edu",
"stars": 0,
"points": 0
},
{
"name": "test2@lewisu.edu",
"stars": 0,
"points": 0
}
],
"sprintstar": "None"
}
]
}
After:
As of your comment I added an example for multiple identifiers:
Test.updateOne({ teamName: "test123" }, {
$set: {
'sprints.$[i].stars.$[j].stars': 5,
'sprints.$[i].sprintstar': "test@lewisu.edu"
}
}, { arrayFilters: [{ "i.sprintum": 1 }, { "j.name": "test@lewisu.edu" }] })
This will update in the array with sprintum one the stars of the person in the stars array with the name "test@lewisu.edu"
With this you can basically do everything you want in all the arrays in your document