【问题标题】:Lodash _.merge function not overwriting properties with updated informationLodash _.merge 函数不会用更新的信息覆盖属性
【发布时间】:2019-06-22 00:51:24
【问题描述】:

在我的用户编辑路线中,我正在尝试使用 Lodash 合并功能来使用 req.body 中发送的更新来更新返回的用户文档(来自 Mongoose)。这是我的代码:

    const { dobYear, dobMonth, dobDay } = req.body;
    const dob = formatDob(dobYear, dobMonth, dobDay);

    const user = await db.User.findById(req.params.id); 

    const updates = pick(req.body, [ 'fullName', 'email', 'password', 'gender', 'address', 'avatar_url' ]);
    merge(user, [updates, dob]);
    let updatedUser = await user.save();

问题是,即使我在请求中发送了更新的电子邮件,合并似乎并没有真正用新的电子邮件值覆盖旧的电子邮件值(来自updates)。

【问题讨论】:

    标签: node.js mongoose lodash put


    【解决方案1】:

    您正在尝试以将参数传递给merge 的方式将对象与数组合并。

    See documentation。我认为您的困惑来自于他们在文档中拥有_.merge(object, [sources]) 的事实。但是,如果您在 Arguments 部分看到它们:

    [sources] (...Object): The source objects. 表示对象列表而不是实际数组。

    试试这个:

    var user = { 'a': 1, 'b': 2 };     
    var updates = { 'a': 3, 'c': 4, 'email': 'aaa@bbb.com' };
    let dob = '11-11-2019'
    
    let result = _.merge(user, updates, {dob});  // <-- ...Object
    
    console.log(result)
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"&gt;&lt;/script&gt;

    【讨论】:

      【解决方案2】:

      merge(user, [updates, dob]);.

      不正确的用法。接受以下内容:

      Arguments
      
          object (Object): The destination object.
          [sources] (...Object): The source objects.
      

      观察...,这意味着它接受可变数量的参数。

      merge(user, updates, { dob })

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-16
        • 2018-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-03
        • 2015-07-02
        相关资源
        最近更新 更多