I have a simple form, that takes 3 string inputs. I bind these to $scope
using ng-model
.
What I want to be able to do, is to set a default value for the string called author in case this is left empty.
If I build my model with only default
, an empty string gets written into my db when the field gets left empty, but when I use require
as well, nothing gets written (db returns an error).
Can anybody explain what I'm doing wrong?
schema:
var wordsSchema = new Schema({
author: {
type: String,
default: 'unknown',
index: true
},
source: String,
quote: {
type: String,
unique: true,
required: true
}
});
express API endpoint:
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!');
}
});
});
if you need additional info, please let me know.
Thanks for the help.
I have a simple form, that takes 3 string inputs. I bind these to $scope
using ng-model
.
What I want to be able to do, is to set a default value for the string called author in case this is left empty.
If I build my model with only default
, an empty string gets written into my db when the field gets left empty, but when I use require
as well, nothing gets written (db returns an error).
Can anybody explain what I'm doing wrong?
schema:
var wordsSchema = new Schema({
author: {
type: String,
default: 'unknown',
index: true
},
source: String,
quote: {
type: String,
unique: true,
required: true
}
});
express API endpoint:
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!');
}
});
});
if you need additional info, please let me know.
Thanks for the help.
Share Improve this question edited Mar 6, 2016 at 14:46 Miha Šušteršič asked Mar 6, 2016 at 14:15 Miha ŠušteršičMiha Šušteršič 10.1k27 gold badges97 silver badges175 bronze badges1 Answer
Reset to default 6The default
value from the schema is only used if the author
field itself isn't present in the new doc. So you'll need to preprocess your received data to get your desired behavior using something like:
var words = {
source: req.body.source,
quote: req.body.quote
};
if (req.body.author) {
words.author = req.body.author;
}
var newWords = new Words(words);