Venue.update({_id : venue.id},
{
name : venue.name,
'contact.phone' : venue.contact.formattedPhone
}, {upsert: true}).exec()
在此代码中,如果 field 没有电话,则不会执行更新插入操作。我怎样才能避免这种情况?如果该字段不为空,我想更新该字段,但如果为空,则不包含该字段。
编辑:
Venue.update({_id : venue.id},
{
name : venue.name,
'contact.phone' : ((!venue.contact.formattedPhone)?
'' : venue.contact.formattedPhone)
}, {upsert: true, safe:false}).exec()
这段代码工作正常,但这次,“电话”字段是“”。我想要的是,如果未定义字段,则隐藏该字段。
最佳答案
以编程方式构建您的 update
对象,以便在未提供时不包含 'contact.phone'
:
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();
关于node.js - Mongoose 更新时如何允许空字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13824452/