node.js - 在 mongoDB 中获取具有 id 数组的集合中的对象

标签 node.js mongodb express data-modeling

使用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
                });
            });
        });
    });
};

最佳答案

也许这更像是它?

exports.findItemsByUserId = function(req, res) {
  var userId = "51e101df2914931e7f000003"; //Just for testing
  var user = db.users.find({"_id": userId});

  var items = db.items.find({'_id': {'$in' : user.useritems}});
  res.send(items.toArray());
};

关于node.js - 在 mongoDB 中获取具有 id 数组的集合中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17725413/

相关文章:

javascript - 访问 API JSON 响应值

node.js - Rest Api 最佳实践 - 将日期作为查询参数传递

arrays - 如何更新 MongoDB 中的多级嵌套数组?

node.js - 在node.js express中,默认路由器总是跳转到index.html静态文件

node.js - Loopback API Explorer 身份验证

node.js - 无法让 Node 应用程序在 openshift 上运行,错误 : listen EACCES

javascript - 更新子文档后保存文档mongoose,mongodb

regex - 使用带有正则表达式的变量在 mongodb 中查找数据(Meteor 应用程序)

javascript - 如何在某些路径上而不是其他路径上在 ExpressJS 中提供静态文件

node.js - 从nodejsexpress登录cakephp