【问题标题】:Using MongoDB ObjectIds with lodash将 MongoDB ObjectIds 与 lodash 一起使用
【发布时间】:2018-08-25 12:08:01
【问题描述】:

在使用 ObjectIds 和 lodash 时,我总是遇到麻烦。假设我有两个对象数组,我想将 lodash _.unionBy() 与:

var arr1 = [
    {
        _id: ObjectId('abc123'),
        old: 'Some property from arr1',
    },
    {
        _id: ObjectId('def456'),
        old: 'Some property from arr1',
    },
];

var arr 2 = [
    {
        _id: ObjectId('abc123'),
        new: 'I want to merge this with object in arr1',
    },
    {
        _id: ObjectId('def456'),
        new: 'I want to merge this with object in arr1',
    },
];

var res = _.unionBy(arr1, arr2, '_id');

结果

console.log(res);
/*
[
    {
        _id: ObjectId('abc123'),
        old: 'Some property from arr1',
    },
    {
        _id: ObjectId('def456'),
        old: 'Some property from arr1',
    },
    {
        _id: ObjectId('abc123'),
        new: 'I want to merge this with object in arr1',
    },
    {
        _id: ObjectId('def456'),
        new: 'I want to merge this with object in arr1',
    },
]
*/

想要的结果

[
    {
        _id: ObjectId('abc123'),
        old: 'Some property from arr1',
        new: 'I want to merge this with object in arr1',
    },
    {
        _id: ObjectId('def456'),
        old: 'Some property from arr1',
        new: 'I want to merge this with object in arr1',
    },
]

由于 ObjectId 是对象,并且在许多情况下(例如,从 MongoDB 获取文档并与本地种子进行比较以进行测试时),它们并不指向相同的引用,因此我不能使用 '_id' 作为迭代对象。

如何使用带有 ObjectID 的 lodash 来达到预期的效果?

【问题讨论】:

  • 我猜你需要像_.unionBy(... x => String(x._id))这样的东西

标签: javascript mongodb lodash


【解决方案1】:

试试这个,我删除了 ObjectId,因为它在 javascript 中不起作用。您可以使用 .toString 进行字符串转换。

var arr1 = [{
        _id: 'abc123',
        old: 'Some property from arr1',
    },
    {
        _id: 'def456',
        old: 'Some property from arr1',
    },
];

var arr2 = [{
        _id: 'abc123',
        new: 'I want to merge this with object in arr1',
    },
    {
        _id: 'def456',
        new: 'I want to merge this with object in arr1',
    },
];


const data = arr2.reduce((obj, ele) => {
    if (!obj[ele._id]) obj[ele._id] = ele.new;
    return obj;
}, {})

arr1 = arr1.map((d) => {
    if (data[d._id]) {
        d.new = data[d._id];
    }
    return d;
})

console.log(arr1);

【讨论】:

    【解决方案2】:

    您必须使用_.unionWith,它允许您使用自定义比较器。使用自定义比较器检查两个 ObjectId 之间的相等性:

    _.unionWith(arr1, arr2, (arrVal, othVal) => arrVal._id.equals(othVal._id));
    

    希望对你有帮助。

    【讨论】:

    • 谢谢你,我不太明白 Comperators 是如何工作的。不幸的是,它并没有帮助。 union 似乎是错误的路径,因为它只创建了一个唯一值数组。它不会合并看起来的对象。
    【解决方案3】:

    这最终解决了我的问题。

    var res = arr1.map(a => {
      return _.assign(a, _.find(arr2, { _id: a._id }));
    });
    

    感谢Tushar's answer

    【讨论】:

      猜你喜欢
      • 2015-03-25
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      • 2021-09-20
      • 2014-08-14
      相关资源
      最近更新 更多