Stack Overflow 사이트를 클론코딩 하는 pre-project를 진행하던 중 목업은 거의 완성이 되어가는데 아직 서버에서 데이터를 가져올 수 없는 상황이라 json-server를 이용하여 가짜 서버를 만드려 한다.
먼저 json-server를 설치하는데, window와 mac의 설치 커멘드가 다르다.
window
$ npm install -g json-server
mac
$ sudo npm install -g json-server
다음으로 프로젝트 루트 위치(src 폴더의 바깥쪽)에 json 파일을 만든다.
간단하게 테스트 해보려면 npm json-server 사이트에서 예시를 복붙해서 사용하면 된다.
아래의 데이터는 stack exchange api를 이용해서 데이터를 가져왔다.
// db.json "items": [ { "tags": [ "node.js", "mongodb", "mongoose" ], "owner": { "account_id": 11503332, "reputation": 653, "user_id": 8430441, "user_type": "registered", "profile_image": "https://www.gravatar.com/avatar/9e40664b473a67a24a1a1c02ace86c6e?s=256&d=identicon&r=PG&f=1", "display_name": "Nick", "link": "https://stackoverflow.com/users/8430441/nick" }, "is_answered": false, "view_count": 2, "up_vote_count": 0, "answer_count": 0, "score": 0, "last_activity_date": 1681982641, "creation_date": 1681982641, "question_id": 76062533, "body_markdown": "I need a little help. I've a collection which has a field **dimension** and that field contains array of different objects, which looks like this\r\n\r\nCollection - 1:\r\n\r\n [\r\n {\r\n "_id": {\r\n "$oid": "6423cddbf4db0d397b22390a"\r\n },\r\n "dimension": [\r\n {\r\n "_id": {\r\n "$oid": "6423cde4f4db0d397b22390b"\r\n },\r\n "dimensionChild": "Wedding"\r\n },\r\n {\r\n "_id": {\r\n "$oid": "6423ce0af4db0d397b22390c"\r\n },\r\n "dimensionChild": "Business Casual"\r\n },\r\n {\r\n "_id": {\r\n "$oid": "6423ce18f4db0d397b22390d"\r\n },\r\n "dimensionChild": "Formal"\r\n }\r\n ]\r\n },\r\n ......\r\n ]\r\n \r\n\r\nand in other object where I've available ids from above document (collection - 1) in form of array, which looks likes this,\r\n\r\nCollection - 2:\r\n\r\n [\r\n {\r\n "productTags": [\r\n {\r\n "$oid": "6423ce0af4db0d397b22390c" // id from above doc\r\n },\r\n {\r\n "$oid": "6423b723f226c91a55d756bc" // id from different document\r\n }\r\n ]\r\n }\r\n ]\r\n\r\nNow I need some data like below,\r\n\r\n [\r\n {\r\n "_id": {\r\n "$oid": "6423ce0af4db0d397b22390c"\r\n },\r\n "dimensionChild": "Business Casual"\r\n },\r\n {\r\n "_id": {\r\n "$oid": "6423b723f226c91a55d756bc"\r\n },\r\n "dimensionChild": "Business Casual 2"\r\n }\r\n ]\r\n\r\nCan anyone pls help me to do this. I was using aggregation pipeline to fetch that and my attempt was something like below,\r\n\r\n await MODEL.aggregate([\r\n .....,\r\n {'$lookup': { "from": 'TEAGET_COLLECTION', "localField": 'productTags', "foreignField": 'dimension._id', as: 'dimensions' } },\r\n .....,\r\n ])\r\n\r\nand this actually returning me whole collection 1's dimension and also those records whose id was not present in Collection - 2's productTags. \r\n\r\nCan anyone please help me to know more about this query.\r\n\r\nThanks,\r\nSoham Roy", "link": "https://stackoverflow.com/questions/76062533/mongo-query-to-get-only-selected-objects-from-same-or-different-documents", "title": "Mongo query to get only selected objects from same or different documents", "body": "<p>I need a little help. I've a collection which has a field <strong>dimension</strong> and that field contains array of different objects, which looks like this</p>\n<p>Collection - 1:</p>\n<pre><code>[\n {\n "_id": {\n "$oid": "6423cddbf4db0d397b22390a"\n },\n "dimension": [\n {\n "_id": {\n "$oid": "6423cde4f4db0d397b22390b"\n },\n "dimensionChild": "Wedding"\n },\n {\n "_id": {\n "$oid": "6423ce0af4db0d397b22390c"\n },\n "dimensionChild": "Business Casual"\n },\n {\n "_id": {\n "$oid": "6423ce18f4db0d397b22390d"\n },\n "dimensionChild": "Formal"\n }\n ]\n },\n......\n]\n</code></pre>\n<p>and in other object where I've available ids from above document (collection - 1) in form of array, which looks likes this,</p>\n<p>Collection - 2:</p>\n<pre><code>[\n {\n "productTags": [\n {\n "$oid": "6423ce0af4db0d397b22390c" // id from above doc\n },\n {\n "$oid": "6423b723f226c91a55d756bc" // id from different document\n }\n ]\n }\n]\n</code></pre>\n<p>Now I need some data like below,</p>\n<pre><code>[\n {\n "_id": {\n "$oid": "6423ce0af4db0d397b22390c"\n },\n "dimensionChild": "Business Casual"\n },\n {\n "_id": {\n "$oid": "6423b723f226c91a55d756bc"\n },\n "dimensionChild": "Business Casual 2"\n }\n]\n</code></pre>\n<p>Can anyone pls help me to do this. I was using aggregation pipeline to fetch that and my attempt was something like below,</p>\n<pre><code>await MODEL.aggregate([\n .....,\n {'$lookup': { "from": 'TEAGET_COLLECTION', "localField": 'productTags', "foreignField": 'dimension._id', as: 'dimensions' } },\n .....,\n])\n</code></pre>\n<p>and this actually returning me whole collection 1's dimension and also those records whose id was not present in Collection - 2's productTags.</p>\n<p>Can anyone please help me to know more about this query.</p>\n<p>Thanks,\nSoham Roy</p>\n" },
데이터가 준비 완료 되었으면 서버를 실행시켜야 한다.
// 리액트의 개발 서버가 보통 3000번 포트를 사용하기 때문에 3000을 제외한 다른 포트를 사용
$ json server --watch db.json --port 4000
서버가 성공적으로 열리면 아래와 같이 연결 되었다고 알려준다.
마지막으로 간단한 get 요청을 해보았다.
const [listData, setListData] = useState([]);
const data = () => {
axios
.get(
"http://localhost:4000/items"
)
.then((res) => {
setListData([...res.data])
})
.catch((err) => {
console.log(err);
});
};
useEffect(() => {
data();
}, []);
요청이 완료되었는지 에러가 발생하였는지 아래와 같이 확인 할 수 있다.
이제 서버는 정상적으로 구동하니까 post, delete 등등.. 기능 구현을 해봐야겠다.