我正在使用以下堆栈创建一个webapp:
我已将应用程序构建为MVC结构。在应用程序中,我需要创建(post)和更新(放置)我从res.body获取的数据值并将它们复制到Mongoose Model。例如,我正在做以下事情:
猫鼬模型:
let mongoose = require('mongoose');
let customerPaymentType = mongoose.Schema({
type: { type: String, required: true, unique: true}
},
{
timestamps: true
}
);
module.exports = mongoose.model('CustomerPaymentType', customerPaymentType);
控制器(仅限部分):
let mongoose = require('mongoose');
let CustomerPaymentType = mongoose.model('CustomerPaymentType');
class CustomerPaymentTypeController {
constructor(){}
create(req, res){
let customerPaymentType = new CustomerPaymentType();
this._setCustomerPaymentType(req.body, customerPaymentType);
customerPaymentType.save(error=>{
if (error) res.send(error);
res.json({
message: 'Customer payment type successfully created',
customerPaymentType:{_id: customerPaymentType._id}
});
});
}
//private methods
_setCustomerPaymentType(rawCustomerPaymentType, customerPaymentType){
if (typeof rawCustomerPaymentType.type !== 'undefined') customerPaymentType.type = rawCustomerPaymentType.type.trim();
}
}
module.exports = CustomerPaymentTypeController;
在这个模型中只有一个字段,因此使用控制器文件中req.body的数据填充模型很容易。但我有其他模型有超过30个字段,并且需要很长时间来填充它们。是否有更简单的方法来处理重新填充模型,类似于Ruby on Rails中的模型?