使用 node.js/express 和 mongoDB 构建 API。我有两个具有多对多关系的集合,用户和项目。我想获取用户关注的所有项目。用户 Items 是一个数组,其 id 引用 Items。
我如何查询以便获得 useritems 数组中的所有项目?
收藏:
用户:
{
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
});
});
});
});
};