mongodb+express - mongoose not saving 'default' value

Viewed 5650

I have a simple form, that takes 3 string inputs. I bind these to $scope using ng-model.

What I want to be able to do, is to set a default value for the string called author in case this is left empty.

If I build my model with only default, an empty string gets written into my db when the field gets left empty, but when I use require as well, nothing gets written (db returns an error).

Can anybody explain what I'm doing wrong?

schema:

var wordsSchema = new Schema({
  author: {
    type: String,
    default: 'unknown',
    index: true
  },
  source: String,
  quote: {
    type: String,
    unique: true,
    required: true
  }
});

express API endpoint:

app.post('/API/addWords', function(req, res) {
    //get user from request body
    var words = req.body;

    var newWords = new Words({
        author: words.author,
        source: words.source,
        quote: words.quote
    });

    newWords.save(function(err) {
        if (err) {
            console.log(err);
        } else {
            console.log('words saved!');
        }
    });
});

if you need additional info, please let me know.

Thanks for the help.

1 Answers
Related