我有一个对象传递给一个函数,并且想用这些值保存一个数据库条目,并且有一些默认选项。在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();
}
这是绝对可怕的代码。什么是更好的写作方式,没有重复?
询问了猫鼬的解决方案,得到猫鼬的答复,不接受为正确:( –
问来提高代码,猫鼬只有thereason为什么我想改善它,如果我想知道如何在Mongoose中进行默认设置我会得到一个不同的标题,我询问了有关改进此代码的信息,而不是为了不必改进它。 – Merc
您的问题应该是“如何在JavaScript中合并对象”。 –