Location in mongoose, mongoDB

后端 未结 3 1446
再見小時候
再見小時候 2020-12-20 17:51

Whenever I try to store a location in my mongodb it doesn\'t show, so I guess I\'m doing something wrong. I can\'t find any documentation on how to store a location in mongo

相关标签:
3条回答
  • 2020-12-20 18:20

    I fixed it myself.

    I did this in my model:

    loc :  { type: {type:String}, coordinates: [Number]},
    

    Underneath I made it a 2dsphere index.

    eventSchema.index({loc: '2dsphere'});
    

    And to add data to it:

    loc: { type: "Point", coordinates: [ longitude, latitude ] },
    
    0 讨论(0)
  • 2020-12-20 18:28

    Looks like your comment is correct (maybe), but the syntax for the index schemetype

    here: http://mongoosejs.com/docs/api.html#schematype_SchemaType-index

    It only accepts Object, Boolean, String

    The correct syntax should be I think

    var eventSchema = new Schema({ 
            location: { type: [Number], index: { type: '2dsphere', sparse: true}}
    )
    

    based on the example in the docs.

    0 讨论(0)
  • 2020-12-20 18:46

    Citing from the mongoose documentation for defining coordinates in schema, I'd like to make a tiny addition to @Laurenswuyts' answer for the 'type' property.

    const exampleSchema = new mongoose.Schema({
      location: {
        type: {
          type: String, // Don't do `{ location: { type: String } }`
          enum: ['Point'], // 'location.type' must be 'Point'
          required: true
        },
        coordinates: {
          type: [Number],
          required: true
        }
      }
    });
    

    Instead of leaving the 'type' property of 'location' open-ended with 'type: String', defining it with a single option enum 'Point' and setting 'required' to 'true' makes the code more robust. Then you would create index and add data the same way @Laurenswuyts did.

    0 讨论(0)
提交回复
热议问题