mongodb+express - 猫鼬不保存“默认”值

Mih*_*šič 7 javascript mongoose node.js express

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

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

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

有人能解释我做错了什么吗?

架构:

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

快速 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!');
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

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

谢谢您的帮助。

Joh*_*yHK 6

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

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

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

var newWords = new Words(words);
Run Code Online (Sandbox Code Playgroud)