0

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.

j-p
  • 3,698
  • 9
  • 50
  • 93

1 Answers1

0

For Updating current : true to current:false

Please change the query.

 db.getCollection('user').update( {
    "_id" : id,
    "schools.current": true }, 
    {$set: {'schools.$.current': false}});
IftekharDani
  • 3,619
  • 1
  • 16
  • 21
  • This is work for me . I had check on mongoDB Tool(robo3T) – IftekharDani Sep 18 '18 at 06:53
  • This should work indeed. If it doesn't update your record then there's something wrong with the `_id` you're passing in. You might want to run this query from another client and/or log your queries to see if what Mongoose actually sends to MongoDB: `db.setLogLevel(1)`. – dnickless Sep 18 '18 at 07:18