node.js 根据数组元素查找对象,只返回匹配的数组元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15213089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:45:01  来源:igfitidea点击:

Find object based on array element, return only matching array element?

node.jsmongodbmongoose

提问by lostintranslation

I have a Person object in mongoose, and that person object has multiple things (each thing has a unique ID).

我在 mongoose 中有一个 Person 对象,并且那个 person 对象有多个东西(每个东西都有一个唯一的 ID)。

person1 = {
  things[{id: 1, name: 'one'},{id:2, name: 'two'}]
}
person2 = {
  things[{id: 3, name: 'three'},{id:4, name: 'four'}]
}

then query:

然后查询:

Person.findOne({'things.id': 2},{'things.$': 1}, function(err, person) { ...

This works great but I am searching through all Person objects (which there could be a lot of). In this case I know the id of the Person I need and some unique id of a 'thing'. Its probably a lot faster to get the Person by id:

这很好用,但我正在搜索所有 Person 对象(可能有很多)。在这种情况下,我知道我需要的人的 id 和“事物”的一些唯一 id。通过 id 获取 Person 可能要快得多:

Person.findById(personId, function(err, person) { ...

Then loop over all the things to find the right one:

然后遍历所有内容以找到正确的内容:

var thing
person.things.forEach(function(t) {
  if (t.id == thingId) {
    thing = t;
  }
});

What I am wondering is if there is a better way. I.E. can I query the Person collection by id to get just one Person then filter out just the thing I am looking for (without the ugly loop)?

我想知道是否有更好的方法。IE 是否可以通过 id 查询 Person 集合以获得一个 Person 然后过滤掉我正在寻找的东西(没有丑陋的循环)?

回答by JohnnyHK

You can include both id terms in a single query and the single element projection will still work:

您可以在单个查询中包含两个 id 术语,并且单元素投影仍然有效:

Person.findOne({_id: personId, 'things.id': 2}, {'things.$': 1}, 
    function(err, person) { ...