2013-07-18 5 views
2

node.js/express와 mongoDB를 사용하여 API를 작성하는 중입니다. 나에게는 많은 관계, 사용자 및 항목과 같은 두 개의 모음이 있습니다. 사용자가 따라 다니는 모든 항목을 가져오고 싶습니다. 사용자 Items는 항목을 참조하는 ID가있는 배열입니다.mongoDB에서 id 배열을 가진 콜렉션의 객체를 가져옵니다.

어떻게해야합니까 그래서 나는 모든 아이템 thats 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" 
} 

편집 : 나는 코드를 업데이트

. 이제 사용자 ID를 기반으로 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 
       }); 
      }); 
     }); 
    }); 
}; 

답변

0

문제가 해결되었습니다. 가장 멋진 솔루션은 아니지만 작동합니다. 그냥 일부 배열을 반복합니다. 이것에 대한 적절한 질문이 있다고 생각해보십시오.

exports.findItemsByUserId = function(req, res) { 
    var id = req.params.id; //<--- was disabled, it will give an error when testing this code. 

    var userId = "51e6a1116074a10c9c000007"; //Just for testing 

    db.collection('users', function(err, collection) { 
     collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, user) { 

      db.collection('items', function(err, collection) { 
       var itemsArray = [] 

       var itemIds = user.useritems 

       for (var i = 0; i < itemIds.length; i++) { 
        itemIds[i] 

        collection.findOne({'_id':new BSON.ObjectID(itemIds[i])}, function(err, item) { 

        itemsArray.push(item); 

        if(itemIds.length === itemsArray.length){ 

         res.send(itemsArray); 

        } 

        }); 
       }; 

      }); 
     }); 
    }); 
}; 
0

어쩌면이게 더 비슷할까요?

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()); 
}; 
+0

그건 작동하지 않습니다. 나는 mongoDB와 nosql 데이터베이스가 처음이다. exampel에 대한 MySql에서 userid와 table을 외래 키로 만든다. 하지만 난 mongoDB와 협력 관계를 얻을 수 없다 – Bullfinch

+0

무엇이 오류입니까? – sje397

+0

아직도 얻는다; TypeError : 정의되지 않은 메서드 'find'를 호출 할 수 없습니다. – Bullfinch

관련 문제