Javascript mongodb+;快速-猫鼬不保存';默认值';价值
我有一个简单的表单,需要3个字符串输入。我使用Javascript mongodb+;快速-猫鼬不保存';默认值';价值,javascript,node.js,express,mongoose,Javascript,Node.js,Express,Mongoose,我有一个简单的表单,需要3个字符串输入。我使用ng model将它们绑定到$scope 我希望能够做的是为名为author的字符串设置一个默认值,以防该字符串为空 如果我只使用默认值构建模型,则当字段留空时,会将空字符串写入数据库,但当我同时使用require时,不会写入任何内容(数据库返回错误) 谁能解释我做错了什么 模式: var wordsSchema = new Schema({ author: { type: String, default: 'unknown',
ng model
将它们绑定到$scope
我希望能够做的是为名为author的字符串设置一个默认值,以防该字符串为空
如果我只使用默认值
构建模型,则当字段留空时,会将空字符串写入数据库,但当我同时使用require
时,不会写入任何内容(数据库返回错误)
谁能解释我做错了什么
模式:
var wordsSchema = new Schema({
author: {
type: String,
default: 'unknown',
index: true
},
source: String,
quote: {
type: String,
unique: true,
required: true
}
});
express 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!');
}
});
});
如果你需要更多的信息,请告诉我
感谢您的帮助。仅当新文档中不存在作者
字段时,才会使用架构中的值。因此,您需要对接收到的数据进行预处理,以获得所需的行为,方法如下:
var words = {
source: req.body.source,
quote: req.body.quote
};
if (req.body.author) {
words.author = req.body.author;
}
var newWords = new Words(words);
那么,如果我想在第一次运行应用程序时将默认值加载到数据库中,我该怎么办呢?非常感谢您在文档中提供了指向该页面的链接。在文档的其他地方似乎没有链接到它!