라벨이 MongoDB인 게시물 표시

[MongoDB] MongoDB Altas 와 mongoose 같이 사용시 documents가 제대로 저장 안될 경우

이미지
프로젝트를 진행하던 중 특정 Collection에서 데이터가 정상적으로 저장되지 않는 문제가 발생했었다.  자세히 설명하자면 videos Collection에 사용자가 업로드한 영상에 관련한 데이터들을 담아야하는데 따로 업로드 횟수 제한등을 설정하지 않았는데도 불구하고 한명의 유저가 여러개의 영상을 업로드 하더라도 단하나의 Documents만 생성되는것이었다. DB에는 사용자가 업로드한 영상이 제대로 들어와서 저장되었지만 mongoDB Atlas에서 videos Collection에 Documents가 유저별로 단 하나씩만 생성되고 추가로 업로드하는 영상에대한 Documents가 생성되지 않는 문제가 발생했었다. 따로 에러코드가 발생하지도 않아서 내가 코드를 잘못 작성해서 그런가 싶어서 프론트에서 넘긴 데이터가 백엔드쪽으로 제대로 전달이 안되고있는건가 콘솔을 다 찍어보면서 확인해 보고 인터넷에 검색해 봤지만 몇 시간 동안 해결방법을 못 찾았다. 그러던 중 무심코 지나쳤던 MongoDB Atlas Collection에  탭들이 보였다. 그 중 indexes 탭을 눌러봤는데 mongoose로  schema model을 작성할 때 초반에 nickname에 실수로 unique 속성을 작성한것이 그대로 mongoDB Atlas에 저장되어있던것이었다.  schema model에 unique가 작성되어있는 상태에서 이미 데이터가 하나 저장되어있었고 그 후에 내 코드 편집기에서 unique 속성을 수정했지만 이미 데이터를 하나 저장하면서 MongoDB Atlas 에는 해당 unique 속성이 적용되어있었기 때문에 유저별로 하나씩의 Document만 저장되는 것이었다. 옆에 Drop index를 눌러 unique 속성을 지우고 다시 시도해보니 내가 원하던데로 저장이 되었다. 이미 수정을 모두 마친뒤라 위에 users Collection으로 사진을 대체했다. 아래는 User.js 모델 const mongoose = require ( " mongoose "

[MongoDB] Mongoose(몽구스) findByIdAndUpdate, findOneAndUpdate 사용해서 documents field 값 업데이트하기

이미지
Video.js(model) const mongoose = require ( " mongoose " ) ; const Schema = mongoose . Schema ; const videoSchema = mongoose . Schema ( { writer : { type : Schema . Types . ObjectId , ref : " User " , }, nickname : { type : String , }, title : { type : String , maxlength : 50 , }, description : { type : String , }, genre : { type : String , }, cost : { type : Number , }, filePath : { type : String , }, views : { type : Number , default : 0 , }, duration : { type : String , }, thumbnail : { type : String , }, preview : { type : String , }, likes : { type : Number , default : 0 , }, }, { timestamps : true } ) ; const Video = mongoose . model ( " Video " , videoSchema) ; module.exports = { Video }; routes/video.js (rout

[MongoDB] Mongoose(몽구스) populate 사용해서 다른 collection의 documents ObjectId 참조하기

이미지
Mongoose(몽구스)에서 populate을 사용하면 다른 Collection에 있는 documents의 ObjectId를 이용하여 documents 참조가 가능하다. 조금 더 보충하자면 MongoDB 자체에서 Documents 마다 자동으로 만들어주는 고유값인 ObjectId가 있는데 다른 Collection에서 populate 메서드를 사용해서 하나의 Documents에 또 다른 Documents의 정보들을 같이 담을 수 있게 해준다. example) User.js (Model) const mongoose = require ( " mongoose " ) ; const bcrypt = require ( " bcrypt " ) ; const saltRounds = 10 ; const jwt = require ( " jsonwebtoken " ) ; const userSchema = mongoose . Schema ( {      email : {      type : String ,      unique : 1 ,      },      name : {      type : String ,      },      nickname : {      type : String ,      unique : 1 ,      },      password : {      type : String ,      minlength : 6 ,      },      eventAgreement : {      type : Boolean ,      },      createdAt : {      type : Number ,      },      google : {      type : String ,      },      github : {  

[MongoDB] Error: No available formula or cask with the name "mongodb".

이미지
Homebrew를 사용하여 MongoDB를 설치할 수 있다. $ brew update && brew install mongodb 하지만 터미널에 에러를 뿜는다.. Error: No available formula or cask with the name "mongodb". ==> Searching for a previously deleted formula (in the last month)... Error: No previously deleted formula found. ==> Searching taps on GitHub... Error: No formulae found in taps. 해결 방법 아래 코드를 순서대로 터미널에 입력하여 설치하면 된다. brew services stop mongodb brew uninstall mongodb brew tap mongodb/brew brew install mongodb-community brew services start mongodb-community 최종적으로 잘 설치 되었는지 확인을 해보려면  $ mongo -version // MongoDB shell version v4.4.1 잘 나오는것을 확인할 수 있다. 한가지 또다른 방법은 $ brew list 를 통해 설치되어있는 파일들을 확인하는것이다.

[MongoDB] Mongoose 연결 에러 ( MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. )

Mongoose 로 MongoDB 연결시 에러  MongoDB를 Mongoose를 사용하여 연결해주었다. 원래 잘 작동했었는데 갑자기 에러 메세지를 뿜었다. Example app listening at http://localhost:5000 [0] MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. 찾아보니 mongoDB 연결시에 맨처음에 아이피 주소를 설정해줬었는데  집에서만 맨날 공부하다가 오랜만에 카페에 나왔더니 아이피 주소가 변경되어서 접속이 안된것이었다. mongoDB 사이트에 접속해서 해당 cluster에서 Network Access로 들어가서    ADD IP ADDRESS ADD IP ADDRESS 버튼을 클릭하여 맥의 경우  시스템 환경설정 -> 네트워크 에 접속하여 현재 연결된 Wi-Fi 의 IP 주소를 복사여 추가해준다.