I want to make sure only ONE item in an array is marked as "current". So my thinking is that IF the incoming data is marked "current = true" then I want to change ALL the other items to "current = false".
the data looks like this:
{
_id:123,
name:"bob jones",
schools:[
{
name: "central HS",
current: false
},
{
name: "east side HS",
current: true
}
]
}
So if I were to add a school - I would want to make sure the existing schools were marked as current: false - ONLY if the incoming school was marked current: true.
incoming object looks like this:
{
name: "Discipline Military Academy HS",
current: true
}
Here is the code I am attempting to use. I do not get an error - but the existing schools with current=true remain, no change. So it appears to NOT be working
NOTE: The id passed in is the person's _id (_id:123)
module.exports.addSchool = function( id, data, callback ) {
// reset all the other "currents" to false (only ONE current school permitted)
if ( typeof data.current != 'undefined' && data.current === true ) {
// NOTE: a console.log('here'); shows I'm getting past the conditional...
User.update( {_id: id}, {$set: {'schools.0.current': false}} );
}
User.findByIdAndUpdate( id, {
$addToSet: {
"schools": data
}
}, {new: true}, callback );
}
Any suggestions?
NOTE: I am using mongoose 5.2.13 to connect my express app to mongoDB and I do get this warning - (node:14508) DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.
But Im not using "findAndModify" - so I do not think this applies, although I am curious why it displays.