简体   繁体   中英

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) => {}
      )

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 } }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM