简体   繁体   English

mongodb + express - mongoose不保存'default'值

[英]mongodb+express - mongoose not saving 'default' value

I have a simple form, that takes 3 string inputs. 我有一个简单的表单,需要3个字符串输入。 I bind these to $scope using ng-model . 我使用ng-model将它们绑定到$scope

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. 我希望能够做的是设置一个名为author的字符串的默认值,以防它被留空。

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). 如果我只用default构建我的模型,当字段变空时,空字符串会写入我的数据库,但是当我使用require时,没有任何内容被写入(db返回错误)。

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: 表达API端点:

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. 仅当新文档中不存在author字段本身时,才使用模式中的default值。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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