将MongoDB ObjectIds与lodash一起使用

时间:2018-03-16 12:12:20

标签: javascript mongodb lodash

使用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',
    },
]

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

如何使用带有ObjectID的lodash来获得所需的结果?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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

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

希望它有所帮助。

答案 2 :(得分:0)

这最终解决了我的问题。

!pwd
/content

!ls 
cat_dog ...

load_files("/content/cat_dog/Colab Notebooks/dataset/training_set")
infinite load

感谢JSON specification