我有这段代码
Requestor.update({ _id: theid }, {$set: {
"reqestmadebyid": doc.reqestmadebyid,
"requestschoolid": doc.requestschoolid,
"requestmadebynames": doc.requestmadebynames,
"requestmadeon": doc.requestmadeon,
"requesttype": doc.requesttype,
"requestdescription": doc.requestdescription,
"requestparameter1": doc.requestparameter1,
"requestparameter2" : doc.requestparameter2,
"requestparameter3" : doc.requestparameter3,
"requestparameter4" : doc.requestparameter4,
"requestparameter5" : doc.requestparameter5,
"requestparameter6" : doc.requestparameter6,
"requestparameter7" : doc.requestparameter7,
"requeststatus" : doc.requeststatus,
"requestdenialexplanation" : doc.requestdenialexplanation
}
});
我用来更新表单。有没有一种方法可以让它像我们在插入过程中那样变小?。
答案 0 :(得分:2)
不能说这个更小,但维护起来更容易。
var fields = [
'reqestmadebyid',
'requestschoolid',
'requestmadebynames',
'requestmadeon',
'requesttype',
'requestdescription',
'requestparameter1',
'requestparameter2',
'requestparameter3',
'requestparameter4',
'requestparameter5',
'requestparameter6',
'requestparameter7',
'requeststatus',
'requestdenialexplanation'
];
var updateSet = fields.reduce(function(data, field) {
return data[field] = doc[field];
}, {});
Requestor.update({ _id: theid }, {$set: updateSet});
使用lodash npm包的更紧凑的例子:
var fields = [
'reqestmadebyid',
'requestschoolid',
'requestmadebynames',
'requestmadeon',
'requesttype',
'requestdescription',
'requestparameter1',
'requestparameter2',
'requestparameter3',
'requestparameter4',
'requestparameter5',
'requestparameter6',
'requestparameter7',
'requeststatus',
'requestdenialexplanation'
];
Requestor.update({ _id: theid }, {$set: _.pick(doc, fields)});