이번에 사이드 프로젝트에서 지도 기능을 만들면서 지도에서 위치 탐색을 해야하는 일이 있었다.
현재 DB로 MongoDB, ODM으로 Mongoose 로 사용하고 있는데 Mognoose가 2차원 구체에서의 Geo-Query를 지원하기 때문에 사용하여 구현하기로 했다.
1. location 필드
2차원 위치 탐색은 경도, 위도 정보를 가진 location 필드가 필요하다.
@Prop({
type: {
type: String,
enum: ['Point'],
default: 'Point',
},
coordinates: {
type: [Number],
required: true,
},
})
location: {
type: 'Point';
coordinates: [number, number]; // [lng, lat]
}
나는 위도,경도 정보가 있으므로 type 을 'Point' 로 했으며 이 외에도 여러 type이 있다.

위도 경도를 사용할 경우엔 위와 같이 구성하면 되고, coordinates 에는 무조건 경도(longitude)가 먼저 와야한다.
2. 인덱스 설정
특정 도큐먼트에서 2차원 위치 탐색을 하려면 2dsphere 인덱스를 적용시켜줘야한다.
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { Schema as MongooseSchema } from 'mongoose';
@Schema({
timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' },
versionKey: false,
})
export class ramenya extends Document {
@Prop({
required: true,
unique: true,
})
name: string;
...중략
@Prop({
required: true,
})
latitude: number;
@Prop({
required: true,
})
longitude: number;
@Prop({
type: {
type: String,
enum: ['Point'],
default: 'Point',
},
coordinates: {
type: [Number],
required: true,
},
})
location: {
type: 'Point';
coordinates: [number, number]; // [lng, lat]
}
...중략
}
export const ramenyaSchema = SchemaFactory.createForClass(ramenya);
ramenyaSchema.index({ location: '2dsphere' });
아래 코드을 통해 인덱스를 적용시킬 수 있다.
ramenyaSchema.index({ location: '2dsphere' });
3. 조회 쿼리 작성
Service 레이어 코드이다.
async getNearByRamenya(latitude: number, longitude: number, radius: number): Promise<getNearByRamenyaResDTO> {Add commentMore actions
const ramenyas = await this.ramenyaModel.find({
location: {
$near: {
$geometry: {
type: 'Point',
coordinates: [longitude, latitude]
},
$maxDistance: radius,
},
},
}).select('name thumbnailUrl genre region address businessHours longitude latitude rating reviewCount')
.populate({
path: 'reviews',
select: 'reviewImageUrls',
options: { limit: 10, sort: { createdAt: -1 }},
match: {
reviewImageUrls: { $ne: [], $exists: true }
}
});
return {
ramenyas: ramenyas,
}
}
\$near, \$geometry 를 통해 연산할 수 있고, 유효 거리를 \$maxDistance 로 설정할 수 있다. \$maxDistance의 단위는 미터이다.
'Backend > Mongoose' 카테고리의 다른 글
| Mongoose aggregate (Find 와 차이) (0) | 2025.07.12 |
|---|