簡體   English   中英

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

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

我有一個簡單的表單,需要3個字符串輸入。 我使用ng-model將它們綁定到$scope

我希望能夠做的是設置一個名為author的字符串的默認值,以防它被留空。

如果我只用default構建我的模型,當字段變空時,空字符串會寫入我的數據庫,但是當我使用require時,沒有任何內容被寫入(db返回錯誤)。

誰能解釋我做錯了什么?

模式:

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

如果您需要其他信息,請告訴我。

謝謝您的幫助。

僅當新文檔中不存在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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM