MongoDB,如果新值不为null,则更新集合字段 [英] MongoDB, update collection field if new value is not null
本文介绍了MongoDB,如果新值不为null,则更新集合字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
仅当新值不为null时,我才会更新设置值的集合。
我有这样的代码:
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 userSurname = req.body.cognome;
var userAddress = req.body.indirizzo;
collection.update(
{_id:ObjectId(req.session.userID)},
{$set: { nome: userName, cognome: userSurname, indirizzo: userAddress }}
)
有没有一种简单的方法可以做到这一点?
Is there an easy way for doing this?
另一种方式:
如果我可以从表格的占位符中取值 req.body。*
数据,我可以解决问题..但这可能吗?
ANOTHER WAY:
if I could take the value req.body.*
from the placeholder of the form where I take the data, I could solve the problem.. but is this possible?
推荐答案
你可以尝试这样的事情:
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 })
这篇关于MongoDB,如果新值不为null,则更新集合字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文