在猫鼬更新时如何允许空字段?

在猫鼬更新时如何允许空字段?

问题描述:

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();