MongoDB, update collection field if new value is not null

前端 未结 8 829
感情败类
感情败类 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:01

    You could try something like this:

    var objForUpdate = {};
    
    if (req.body.nome) objForUpdate.nome = req.body.nome;
    if (req.body.cognome) objForUpdate.cognome = req.body.cognome;
    if (req.body.indirizzo) objForUpdate.indirizzo = req.body.indirizzo;
    
    //before edit- There is no need for creating a new variable
    //var setObj = { $set: objForUpdate }
    
    objForUpdate = { $set: objForUpdate }
    
    collection.update({_id:ObjectId(req.session.userID)}, objForUpdate })
    

提交回复
热议问题