MongoDB 中的 NestJS GeoJSON 类型字段错误

问题描述 投票:0回答:1

我正在使用 NestJS 和@nestjs/mongoose 创建一个需要存储 GeoJSON 坐标的模式。下面是位置模式的模式,它有一个标记为点的字段,它存储点模式

import { Prop, Schema } from '@nestjs/mongoose';
import { ApiProperty } from '@nestjs/swagger';
    
@Schema()
export class PointSchema {
    @ApiProperty()
    @Prop({
        type: String,
        enum: ['Point'],
        default: 'Point',
        required: true
    })
    type: string
  
    @ApiProperty({
        type: [Number, Number]
    })
    @Prop({
        type: [Number, Number],
        required: true,
    })
    coordinates: number[]
}

@Schema()
export class Location {
    @ApiProperty({
        type: PointSchema
    })
    @Prop({
        type: PointSchema
    })
    point: PointSchema

    @ApiProperty()
    @Prop()
    addressShort: string;

    @ApiProperty()
    @Prop()
    addressLong: string;

    @ApiProperty()
    @Prop()
    geohash: string;
}

问题是,当我去保存一个新位置时,我得到一个错误,指出点字段不能转换为对象字段,因为它是一个字符串。

location.point.type:在路径“point.type”处的值“Point”(类型字符串)转换为对象失败,location.point.type.coordinates:路径

point.type.coordinates
是必需的。

我不确定为什么会发生这种情况,但是如果我在保存之前更改对象形状以匹配错误想要的内容

const newLocation:Location = {
    ...location,
    point: {
        type: newPlace.location.point
    }
}

然后它会工作并将 GeoJSON 坐标保存在点的类型字段中。我不确定为什么它试图将整个点对象保存在类型字段中,我担心这将无法索引。以前有没有人遇到过这种情况或使用过 NestJS mongo db 并尝试使用 GeoJSON 对象?谢谢。

node.js mongodb mongoose nestjs geojson
1个回答
0
投票

Mongoose 期望

type
作为一个对象。在您的实现中,它被定义为一个字符串。你需要改变它:

@Schema()
export class PointSchema {
    @ApiProperty()
    @Prop({
        type: {
            type: String,
            enum: ['Point'],
            default: 'Point',
            required: true,
        },
        coordinates: {
            type: [Number],
            required: true,
        },
    })
    point: {
        type: string;
        coordinates: number[];
    };
}

我不确定为什么它试图将整个点对象保存在类型字段中

它试图将整个点对象保存在

type
内的原因是因为
enum
default
属性:

@Prop({
  type: String,
  enum: ['Point'], // only accepts 'Point' as a value
  default: 'Point', // defaults to 'Point' if value is not provided
  required: true
})
type: string
  • 这些属性将

    type
    字段的可能值限制为仅
    'Point'
    ,如果未提供任何值,还将默认值设置为
    'Point'

  • 当您尝试使用

    Location
    保存
    point
    时,
    type
    被设置为
    'Point'
    (这是一个字符串值)。 这就是你出错的原因.

  • 当您仅使用

    type
    创建一个新对象并分配它时,您正在创建一个具有
    enum
    default
    属性所期望的正确形状的新对象。 这就是为什么它在您保存时有效.


我担心这不会被索引。

这取决于你打算如何查询。

  • 如果您打算根据
    type
    进行查询,那么将整个
    point
    对象保存在该字段中可能会使查询更加困难。
  • 如果你不打算根据
    type
    查询,那可能无所谓。

只要类型字段存储为字符串而不是对象,它就应该是可索引的。

© www.soinside.com 2019 - 2024. All rights reserved.