MongoDB, update collection field if new value is not null

前端 未结 8 843
感情败类
感情败类 2020-12-29 13:45

I would update a collection setting the value only if the new values are not null. I have a code like this:

 ...
 var userName = req.body.nome;
 var userSurn         


        
8条回答
  •  灰色年华
    2020-12-29 14:02

    Probably you've got already user authenticated so you should have req.user.*

    in this case you can use ternary operator to assign the value and update it with either new one or the current one (so there is no update)

    var userName = req.body.nome ? req.body.nome : req.user.nome;
    var userSurname = req.body.cognome ? req.body.nome : req.user.cognome;
    var userAddress = req.body.indirizzo ? req.body.indirizzo : req.user.indirizzo;
    
    collection.update(
         {_id:ObjectID(req.session.userID)},
         {$set: { nome: userName, cognome: userSurname, indirizzo: userAddress }}
    )
    

    If you don't have req.user then you can do it in 3 steps. 1. find user in collection 2. get current data 3. update data with new or current (as above)

    let currentName
    let currentSurname
    db. collection.findOne({_id: ObjectID(req.session.userID)}, (err, user) => {
        if (err) { } // handle error here
        else if (user) {
            currentName = user.name
            currentSurname = user.surname
        }
    })
    

提交回复
热议问题