【问题标题】:mongodb+express - mongoose not saving 'default' valuemongodb+express - 猫鼬不保存“默认”值
【发布时间】:2016-06-20 01:39:34
【问题描述】:

我有一个简单的表单,需要 3 个字符串输入。我使用ng-model 将这些绑定到$scope

我想要做的是为名为 author 的字符串设置一个默认值,以防它为空。

如果我仅使用default 构建模型,则当字段为空时,一个空字符串会写入我的数据库,但当我也使用require 时,不会写入任何内容(数据库返回错误)。

谁能解释我做错了什么?

架构:

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

快速 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!');
        }
    });
});

如果您需要更多信息,请告诉我。

感谢您的帮助。

【问题讨论】:

    标签: javascript node.js express mongoose


    【解决方案1】:

    仅当 author 字段本身不存在于新文档中时,才会使用架构中的 default 值。因此,您需要使用以下方法预处理收到的数据以获得所需的行为:

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

    【讨论】:

    • 那么,如果我想在第一次运行应用程序时将默认值加载到数据库中该怎么办?
    • 非常感谢您在文档中提供指向该页面的链接。文档中的其他任何地方似乎都没有指向它的链接!
    猜你喜欢
    • 2013-12-08
    • 2020-06-13
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2018-12-03
    • 2022-07-29
    • 2016-05-05
    • 1970-01-01
    相关资源
    最近更新 更多