MongoDB,如果新值不为null,则更新集合字段

Nic*_*ola 9 javascript mongodb node.js

仅当新值不为null时,我才会更新设置值的集合.我有这样的代码:

 ...
 var userName = req.body.nome;
 var userSurname = req.body.cognome;
 var userAddress = req.body.indirizzo;

 collection.update(
     {_id:ObjectId(req.session.userID)},
     {$set: { nome: userName, cognome: userSurname, indirizzo: userAddress }}
 )
Run Code Online (Sandbox Code Playgroud)

这样做有简单的方法吗?

另一种方式:如果我可以req.body.*从我获取数据的表单的占位符中获取值,我可以解决问题..但这可能吗?

Iva*_*Srb 15

你可以尝试这样的事情:

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 })
Run Code Online (Sandbox Code Playgroud)

  • 如果你有很多参数/字段,它可能看起来不太好,你最终会遇到 r/programminghorror (4认同)

Edw*_*ome 5

您可以像其他问题一样使用lodash:/sf/answers/2340300021/

_.pickBy({ a: null, b: 1, c: undefined }, _.identity);

将会

{b:1}