简体   繁体   English

NodeJS中模型的可选更改

[英]Optional Changes to Model in NodeJS

I'm using Nodejs with Sequelizejs but I suppose this question could apply to other situations. 我正在将Nodejs与Sequelizejs一起使用,但我想这个问题可能适用于其他情况。

An object comes in to my method with a some properties attempting to update the model I pull from the database (if I find a match). 一个带有一些属性的对象进入我的方法,尝试更新从数据库中提取的模型(如果找到匹配项)。

var changes = {
   firstName: "foo",
   loginPin: 0000
}

The model contains many more properties but for the sake of this discussion here is an example. 该模型包含更多的属性,但是出于讨论的目的,这里是一个示例。

var existingEmployeeModel = {
    firstName: "bar",
    middleInitial: "f",
    loginPin: 1111,
    email: "foo@bar.com"
}

So right now I basically look at processing it like this: 因此,现在我基本上会考虑像这样处理它:

if (changes.firstName) existingEmployeeModel.firstName = changes.firstName;

Is there a better way to do this? 有一个更好的方法吗? Ocassionally I may .trim() , etc but I can't imagine this is ideal. 有时我可以使用.trim()等,但我无法想象这是理想的选择。

For example, lodash apply http://lodash.com/docs#assign function does something similar. 例如,lodash apply http://lodash.com/docs#assign函数可以执行类似的操作。 Just call it as follows: 只需按如下方式调用它:

_.assign(existingEmployeeModel, changes);

It should copy all the properties from the changes to the model. 它应该将所有属性从changes复制到模型。

If you do not want to add a dependency, you can use this one: 如果不想添加依赖项,则可以使用此依赖项:

function apply(model, changes) {
  Object.keys(changes).forEach(function (key) {
    if ('string' === typeof changes[key]) {
      model[key] = changes[key].trim();
    } else {
      model[key] = changes[key];
    }
  });
}

Done. 完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM