2016-03-06 149 views
1

我有一個簡單的表單,需要3個字符串輸入。我使用ng-model將這些綁定到$scopemongodb + express - 貓鼬不保存「默認」值

我希望能夠做到的是爲被稱爲作者的字符串設置一個默認值,以防留下空白。

如果我只用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!'); 
     } 
    }); 
}); 

,如果你需要更多的信息,請讓我知道。

感謝您的幫助。

回答

1

模式中的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); 
+0

因此,我應該怎麼做, –