使用node.js / express和mongoDB构建API。我有两个集合,一个是用户,一个是项目,它们之间是多对多的关系。我想获取用户正在关注的所有项目。用户项目是一个包含指向项目的ID的数组。
如何查询以获取在用户项目数组中的所有项目?
集合:
- 用户:
如何查询以获取在用户项目数组中的所有项目?
集合:
- 用户:
{
email: "johnny@hotmail.com",
username: "johnny",
useritems: ["51e101df2914931e7f000003", "51cd42ba9007d30000000001"]
}
物品:
{
"name": "myitem",
"description": "Description of item"
"_id": "51e101df2914931e7f000003"
}
{
"name": "myitem2",
"description": "Description of item2"
"_id": "51cd42ba9007d30000000001"
}
{
"name": "myitem3",
"description": "Description of item3"
"_id": "51e101df2914931e7f000005"
}
编辑:
我更新了代码。现在根据用户id获取用户项id的数组。问题是当我尝试将项目发送到数组时,始终为空。我的查询有问题吗?
exports.findItemsByUserId = function(req, res) {
//var id = req.params.id;
var userId = "51e6a1116074a10c9c000007"; //Just for testing
db.collection('users', function(err, collection) {
collection.findOne({'_id':new BSON.ObjectID(userId)}, function(err, user) {
db.collection('items', function(err, collection) {
console.log("user undefined? ",user);
console.log("useritems ",user.useritems);
collection.find({'_id': {'$in' : user.useritems}}).toArray(function(err, items) {
console.log("useritems ",user.useritems); // <--Gets me array with the ids
console.log("items ", items); //<--Empty
res.send(items);//Empty
});
});
});
});
};