los*_*ion 6 mongoose mongodb node.js
我在mongoose中有一个Person对象,那个person对象有多个东西(每个东西都有一个唯一的ID).
person1 = {
things[{id: 1, name: 'one'},{id:2, name: 'two'}]
}
person2 = {
things[{id: 3, name: 'three'},{id:4, name: 'four'}]
}
Run Code Online (Sandbox Code Playgroud)
然后查询:
Person.findOne({'things.id': 2},{'things.$': 1}, function(err, person) { ...
Run Code Online (Sandbox Code Playgroud)
这很好但我正在搜索所有Person对象(可能有很多).在这种情况下,我知道我需要的人的ID和一个'东西'的唯一ID.通过id获取Person可能要快得多:
Person.findById(personId, function(err, person) { ...
Run Code Online (Sandbox Code Playgroud)
然后循环遍历所有事情以找到正确的:
var thing
person.things.forEach(function(t) {
if (t.id == thingId) {
thing = t;
}
});
Run Code Online (Sandbox Code Playgroud)
我想知道的是,如果有更好的方法.我可以通过id查询Person集合来获取一个Person然后过滤掉我正在寻找的东西(没有丑陋的循环)?
Joh*_*yHK 17
您可以在单个查询中包含两个id术语,单个元素投影仍然有效:
Person.findOne({_id: personId, 'things.id': 2}, {'things.$': 1},
function(err, person) { ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21688 次 |
| 最近记录: |