1
Venue.update({_id : venue.id},                         
    {
      name : venue.name,
      'contact.phone' : venue.contact.formattedPhone                      
    }, {upsert: true}).exec()

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.

Edit:

 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.

Burak
  • 5,706
  • 20
  • 70
  • 110
  • Are you using `null`. If so, try `undefined` instead. I guess this thread might help http://stackoverflow.com/questions/12636938/set-field-as-empty-for-mongo-object-using-mongoose – Sushant Gupta Dec 11 '12 at 17:11
  • Can we do something like 'if formattedPhone == undefined than contact.phone is '' ? – Burak Dec 11 '12 at 17:26
  • Actually, I am Django guy who is currently transitting to node.js. I am experienced with mongoengine. I am not yet aware of mongoose much. I guess you too were a Django person switching to Node :) – Sushant Gupta Dec 11 '12 at 17:29
  • Exactly:) I just moved to Node.js and Mongoose – Burak Dec 11 '12 at 17:35
  • I don't understand what behavior you're looking for. Could you give a concrete example? – JohnnyHK Dec 11 '12 at 21:03
  • Let's say, one of a venue object in venues array has no formattedPhone data. So it is undefined. And the venue cannot be saved nor updated. – Burak Dec 11 '12 at 21:09

1 Answers1

0

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();
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471