【发布时间】:2018-02-16 17:06:53
【问题描述】:
我已经为这些问题苦苦挣扎了几个月,现在仍然没有解决方案。
基本上我有 2 个 mongodb 数据库结构。
一个叫做用户,另一个叫做项目。
一个用户可以拥有多个项目。
用户结构简单=
Users = [{
_id: 1,
name: "Sam",
email: "sam@gmail.com",
group: "Rangers"
},
{
_id: 2,
name: "Michael",
email: "michael@gmail.com"
group: "Muse"
},
{
_id: 3,
name: "John",
email: "john@gmail.com"
group: "Merchant"
},
.....
]
Items 结构如下,每个项目都分配给一个用户。
Items = [
{
_id: 1,
user_id: 1,
item_name: "Flying Sword",
timestamp: ...
},
{
_id: 3,
user_id: 1,
item_name: "Invisible Cloak",
timestamp: ...
},
{
_id: 4,
user_id: 2,
item_name: "Iron Shield"
},
{
_id: 5,
user_id: 7,
item_name: "Splashing Gun",
timestamp: ...
},
...
]
我想运行一个猫鼬查询,将用户作为主要对象进行查询。
在返回用户对象的结果后,我想用过滤后的用户查询所有 Items 对象,并将它们作为子文档附加到先前查询的每个用户对象。
比如我要查询
Users.find({group: "Muse"}, function(err, users){
I DON"T KNOW WHAT TO WRITE INSIDE
})
基本上结果应该是:
[
{
_id: 4,
name: "Jack",
email: "jack@gmail.com",
group: "Muse",
items: [
{
_id: 8
name: "Magic Wand",
user_id: 4,
timestamp: ...
}
{
_id: 12
name: "Blue Potion",
user_id: 4,
timestamp: ...
},
{
_id: 18
name: "Teleportation Scroll",
user_id: 4,
timestamp: ...
}
]
}
.....
More USERS of similar structure
]
每个用户最多返回三个按时间戳排序的项目。
先谢谢了,我试了很多次都失败了。
【问题讨论】: