BK52
BK52

Reputation: 934

Mongoose findOneAndUpdate with condition

I have an a simple Model like this,

const userSchema = new mongoose.Schema({
    name:String,   
    personelID:Number,
    departments:{
        type:[String],
    },
})

An user can work multiple departments. For a new department first I control the existing departments array if it not include i push new department.

In the basic way I can do this with

User.findOne({personelID:ID},(err,usr)=>{
             if(err) return console.error(err); 
             if(usr.departments!==undefined){
                if(!usr.departments.includes(department))
                {
                    usr.departments.push(department);
                    usr.save();
                }
             }
})

It works with no problem. But can I do this with simpler like this?

  User.findOneAndUpdate(
      {personelID:ID, 'departments is not include newDepartment'},
      {departments:departments.push(newDepartment)}
      (callback) => {}
      )

Upvotes: 1

Views: 739

Answers (1)

turivishal
turivishal

Reputation: 36104

You can put condition for departments not equal to specific department in query part, $ne will manage condition in array fields also, if department not found then it will push otherwise it will skip push operation.

User.findOneAndUpdate(
    {
        personelID: ID,
        departments: {  $ne: department }
    },
    { $push: { departments: department } }
)

Upvotes: 2

Related Questions