2016-03-06 116 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

因此,我应该怎么做, –