使用node.js/express和mongoDB构建API。我有两个集合,像一个多对多的关系,用户和项目。我想获取用户所关注的所有项目。用户Items是一个数组,其中id指的是Items。使用mongoDB中的id数组获取对象
我如何查询,所以我得到所有的项目多数民众赞成在useritems数组?
类别:
用户:
{
email: "[email protected]",
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"
}
编辑:
我更新的代码。我现在根据用户标识获取useritems 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
});
});
});
});
};
这并不奏效。我是mongoDB和nosql数据库的新手。在MySql for exam我会创建一个useritems表,其中userid和itemid作为外键。但我不能让这些关系与mongoDB工作 – Bullfinch
什么是错误? – sje397
仍然获得; TypeError:无法调用未定义的方法'find' – Bullfinch