5월, 2021의 게시물 표시

MongoDB ObjectId 에서 날짜 추출하는 방법(Swift & java)

 몽고디비의 ObjectId 에서 날짜를 추출하여 사용하는 방법이다. 아이폰을 위한 스위프트 함수로 작성하였다. func ObjectIdToDate(id: String ) -> Date {     var resultDate = Date ()     let endIdx: String . Index = id. index (id. startIndex , offsetBy: 7)     let hex = id[id. startIndex... endIdx]     if let offset = UInt32 (hex, radix: 16) {         resultDate = Date (timeIntervalSince1970: TimeInterval (offset))     }     return resultDate } 안드로이드를 위한 자바로 작성한 코드이다. public Date ObjectIdToDate (String id) { String hex = id.substring( 0 , 8 ) ; Long x = Long. parseLong (hex , 16 ) * 1000 ; return new Date(x) ; } 문자열 중 앞의 8자리가 유닉스 타임의 숫자이다. 서버에서 몽고디비의 _id 값을 Hex 코드로 내려 준다면 당황하지 말고 변환하여 사용하자. 앞의 4바이트가 시간이므로 이를 변환하면 된다. unix epoch 이란 1970.1.1 부터 지나온 시간을 말한다. 대부분 서버에서 이 시간을 사용한다.

Node Express Mongoose 조회가 되지 않을 때

Ubuntu Server 에 Node 를 설치하고 Express 를 사용하여 서비스를 할 예정이다. 데이터베이스는 MongoDB 로 구성되어 있다. Mongoose 를 이용하여 서비스를 구성하려고 하는데 매뉴얼 대로 해도 조회가 되지 않는다. 매뉴얼이 자세하지 않는거 같다. 많은 검색 후에 컬렉션을 설정해야 한다고 하여 했더니 조회가 되었다. var mongoose = require ( 'mongoose' ); var db = mongoose . connection ; db . on ( 'error' , console . error ); db . once ( 'open' , function () { console . log ( 'Connected to mongo server' ); }); mongoose . connect ( 'mongodb://user:password@host:port/dbname' , { useNewUrlParser : true , useUnifiedTopology : true }); var Schema = mongoose . Schema ; var cannonBeeSchema = new Schema ({ _id : Schema . Types . ObjectId , version : String , os : String , locale : String , uuid : String , count : String }); cannonBeeSchema . set ( 'collection' , 'cannonBee' ); var cannonBee = mongoose . model ( 'cannonBee' , cannonBeeSchema ); cannonBee . findOne ({}, function ( err , data ) { if ( err ) return conso