Mongoose - find() 具有多个相同的 id [英] Mongoose - find() with multiple ids that are the same

查看:64
本文介绍了Mongoose - find() 具有多个相同的 id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我用猫鼬执行这个查询;

If I were to perform this query with mongoose;

Schema.find({
    _id: {
        $in: ['abcd1234', 'abcd1234', 'abcd1234']
    }
});

查询只会返回如下内容:

The query will only return something like:

[{
    'property1': 'key1',
    'property2': 'key2'
}]

数组只有一个对象,显然是因为我传入了所有相同的 id.但是,我实际上希望返回重复的对象.我该怎么做?

With the array only having one object, obviously because I passed in all the same id's. However, I actually want duplicate objects returned. How can I do this?

推荐答案

Mongo 本身只会返回没有重复的对象.但是您可以从中构建一个包含重复项的对象数组.

Mongo itself will only return objects with no duplicates. But you can then build an array of objects with duplicates from that.

例如,如果 array 是我的 Mongo 返回的对象数组 - 在这种情况下:

For example, if array is the array of objects returned my Mongo - in this case:

var array = [{
    _id: 'abcd1234',
    property1: 'key1',
    property2: 'key2'
}];

ids 是您想要重复的 ID 列表 - 在您的情况下:

and ids is your list of IDs that you want with duplicates - in your case:

var ids = ['abcd1234', 'abcd1234', 'abcd1234'];

那么你可以这样做:

var objects = {};
array.forEach(o => objects[o._id] = o);
var dupArray = ids.map(id => objects[id]);

现在 dupArray 应该包含重复的对象.

Now dupArray should contain the objects with duplicates.

完整示例:

var ids = ['abcd1234', 'abcd1234', 'abcd1234'];
Schema.find({_id: {$in: ids}}, function (err, array) {
  if (err) {
    // handle error
  } else {
    var objects = {};
    array.forEach(o => objects[o._id] = o);
    var dupArray = ids.map(id => objects[id]);
    // here you have objects with duplicates in dupArray:
    console.log(dupArray);
  }
});

这篇关于Mongoose - find() 具有多个相同的 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆