Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

node.js - Typegoose + nestjs + mongodb: index not creating using @index decorator

I am facing an error with typegoose. I have a model called SP and i have to create 2dsphere index on its property called geoLocation i tried typegoose decorator @index but it is not working even its not throwing any error, i dont know whats happing and how typegoose handles it. Is there any one who give me the solution of it ??.

code:

import { Prop, index, modelOptions, Severity } from '@typegoose/typegoose';
import { BaseModel } from '../base.model';
import { Factory } from 'nestjs-seeder';

export enum SPStatus {
    INAVTIVE = "INAVTIVE",
    ACTIVE = "ACTIVE",
}

@modelOptions({ options: { allowMixed: Severity.ALLOW } })
@index({ geoLocation: '2dsphere' }, {})
export class SP extends BaseModel{
    @Factory(faker => faker.company.companyName())
    @Prop({ required: true, index: true, text: true })
    businessName : string
    
    @Factory(faker => {
        let data = {
            type : "Point",
            coordinates:[Number(faker.address.longitude()), Number(faker.address.latitude())]
        }
        console.log(data);

        return data;
    })
    @Prop({ required: false })
    geoLocation: {
        type: string,
        coordinates: [number]
    }
}
question from:https://stackoverflow.com/questions/65617696/typegoose-nestjs-mongodb-index-not-creating-using-index-decorator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try below code it works for me

@index({ location: '2dsphere' })
export class GPSData extends Typegoose{    
    
    @prop({ required: true })
    public log_Id!: mongoose.Types.ObjectId;

    @ValidateNested({each: true})
    @prop({
        _id : false
    })
    readonly location: Location;
}

export class Location extends Typegoose{  
   
    @prop()
    @IsString({message: " type should be text"})
    readonly type: String;

    @prop({ required: true })
    coordinates: [[Number]];
}

Sample collection (Type can be either one of this "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", and "GeometryCollection"):

{ 
"log_Id": "5fbdec08ce02d61fec9a0189",

"location":{
    "type":"MultiPoint",
    "coordinates":[
 [ -73.9580, 40.8003 ],
 [ -73.9498, 40.7968 ],
 [ -73.9737, 40.7648 ],
 [ -73.9814, 40.7681 ]
 ]  
}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...