LearnBoost/mongoose — Issue #624: defaults are ignored on upsert
Author: jhoff
Created: 2011-11-25 04:37:30+00:00
State: open

As of 2.3.13, default values and type options that are specified in the schema are ignored during an upsert operation when the record is being inserted. Updates to existing records work as expected.

```javascript
//schema declaration

var Schema = require('mongoose').Schema;

var ip_address = "0.0.0.0";

exports.beta_email = new Schema({
email : { type: String, index: true, uppercase: true },
ip_address : { type: String, match: /[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}/, 'default': ip_address },
first_submit : { type: Date, 'default': Date.now },
total_submits : { type: Number, 'default': 1 },
}, { collection: 'beta_email' });

//upsert ( does not write fields with default values ( first_submit, ip_address ) and leaves the email in lowercase )

db.model('beta_email')
.update(
{ email: req.body.email },
{ $inc: { total_submits: 1 } },
{ upsert: true, multi: false },
function(err) {}
);

//produces

{
"_id": ObjectId("4ecf18651b77a21f69254acf"),
"email": "upsert@event.com",
"total_submits": 1
}

// save

var Beta_Email = db.model('beta_email');
var be = new Beta_Email();
be.email = req.body.email;
be.save( function(err) {} );

//produces this:

{
"email": "SAVE@EVENT.COM",
"_id": ObjectId("4ecf1883f04792b1a5000002"),
"ip_address": "0.0.0.0",
"total_submits": 1,
"first_submit": ISODate("2011-11-25T04: 24: 35.707Z")
}

```