我有一个传递给函数的对象,并希望保存带有这些值的数据库条目,并且可以选择默认值。
实际上......
我在Mongoose中有这样的架构:
var Log = new Schema({
workspaceId : { type: String, index: true },
workspaceName : { type: String, index: true },
loginSession : { type: String, index: true },
loginToken : { type: String, index: true },
logLevel : { type: Number, enum:[0,1] },
errorName : { type: String, index: true },
message : { type: String, index: true },
reqInfo : { type: String },
data : { type: String },
loggedOn : { type: Date, index: true },
});
mongoose.model('Log', Log);
要在这张桌子上写东西,我有类似的东西:
exports.Logger = function(logEntry){
var Log = mongoose.model("Log"),
req = logEntry.req;
log = new Log();
// Sorts out log.reqInfo
if ( logEntry.req){
log.reqInfo = JSON.stringify({
info : req.info,
headers: req.headers,
method : req.method,
body :req.body,
route :req.route,
params: req.params
});
} else {
logEntry.reqInfo = {};
}
// Sorts out all of the other fields with sane defaults.
// FIXME: improve this code, it's grown into something ugly and repetitive
log.workspaceId = logEntry.workspaceId ? logEntryworkspaceId. : '';
log.workspaceName = logEntry.workspaceName ? logEntry.workspaceName : '';
log.loginSession = logEntry.loginSession ? logEntry.loginSession : '';
log.loginToken = logEntry.loginToken ? logEntry.loginToken : '';
log.logLevel = logEntry.logLevel ? logEntry.logLevel : 0;
log.errorName = logEntry.errorName ? logEntry.errorName : '';
log.message = logEntry.message ? logEntry.message : '';
log.data = logEntry.data ? logEntry.data : {};
// Sorts out log.loggedOn
log.loggedOn = new Date();
log.save();
}
这绝对是糟糕的代码。在没有重复的情况下编写它的更好的方法是什么?
答案 0 :(得分:10)
我不明白你的代码。因此,如果未设置值,您希望将其设置为空字符串''
?
如果您想要默认设置,最简单的方法就是在架构中定义它们。
var Log = new Schema({
workspaceId : { type: String, index: true, default: 'your default here' },
//...
loggedOn : { type: Date, index: true, default: Date.now }
});
来自docs
答案 1 :(得分:1)
这样的事情可能会更优雅:
创建包含默认值
的字典defaults = {
workspaceName: 'foo',
loginSession: 'bar',
loginToken: 'baz'
};
console.log(defaults)
给出一些值
values = {
workspaceName: 'WNAME1',
loginSession: 'LS1',
somethingElse: 'qux'
};
console.log(values)
如果值不包含任何指定默认值的条目,请将默认值添加到值
for(i in defaults){
if(!values[i]){
values[i] = defaults[i];
}
}
console.log(values)