简体   繁体   中英

mongodb+express - mongoose not saving 'default' value

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.

The default value from the schema is only used if the author field itself isn't present in the new doc. So you'll need to preprocess your received data to get your desired behavior using something like:

var words = {
    source: req.body.source,
    quote: req.body.quote
};

if (req.body.author) {
    words.author = req.body.author;
}

var newWords = new Words(words);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM