mongodb + express – mongoose不保存“默认”值
我有一个简单的表单,需要3个stringinput。 我使用ng-model
将它们绑定到$scope
。
我想要做的是为被称为author的string设置一个默认值,以防空白。
如果我只用default
build立我的模型,当字段被留空时,一个空string被写入到我的数据库中,但是当我使用require
时,没有任何东西被写入(db返回一个错误)。
任何人都可以解释我做错了什么?
模式:
var wordsSchema = new Schema({ author: { type: String, default: 'unknown', index: true }, source: String, quote: { type: String, unique: true, required: true } });
expressionAPI端点:
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);