本文介绍了在猫鼬更新时如何允许空字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Venue.update({_id : venue.id},
{
name : venue.name,
'contact.phone' : venue.contact.formattedPhone
}, {upsert: true}).exec()
在此代码中,如果场馆没有电话,则不会执行Upsert操作.如何避免这种情况?我想更新该字段,如果它不为null,但是如果为null,则不包括该字段.
In this code, if venue has no phone, Upsert operation is not done. How can I avoid this? I want to update that field if it is not null, but if null, just dont include that field.
Venue.update({_id : venue.id},
{
name : venue.name,
'contact.phone' : ((!venue.contact.formattedPhone)?
'' : venue.contact.formattedPhone)
}, {upsert: true, safe:false}).exec()
此代码可以正常工作,但是这次,电话"字段为".我想要的是隐藏未定义的字段.
This code works fine but this time, 'phone' fields are ''. What I want is, hiding the field if it is undefined.
推荐答案
以编程方式构建update
对象,以在不提供时不包含'contact.phone'
:
Build up your update
object programmatically to not include 'contact.phone'
when not provided:
var update = {
name : venue.name
};
if (venue.contact.formattedPhone) {
update['contact.phone'] = venue.contact.formattedPhone;
}
Venue.update({_id : venue.id}, update, {upsert: true, safe:false}).exec();
这篇关于在猫鼬更新时如何允许空字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!