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
});
});
});
});
};
그건 작동하지 않습니다. 나는 mongoDB와 nosql 데이터베이스가 처음이다. exampel에 대한 MySql에서 userid와 table을 외래 키로 만든다. 하지만 난 mongoDB와 협력 관계를 얻을 수 없다 – Bullfinch
무엇이 오류입니까? – sje397
아직도 얻는다; TypeError : 정의되지 않은 메서드 'find'를 호출 할 수 없습니다. – Bullfinch