将坐标保存为mongoose

时间:2016-10-09 20:25:20

标签: node.js mongodb mongoose

我想使用Node.js和mongoose将lat保存到mongodb中。 mongodb坐标应该在最后看起来像这样:

    { "_id" : ObjectId("57faa6b5a005aa179276d25d"),
      "loc" : { "coordinates" : [ 40.730610, -73.935242 ], "type" : "Point" }}

Node.js保存到mongodb但这对我不起作用

   router.post('/setData',function(req,res){

     exp = test();
     exp.loc = {"loc":{"type":"Point","coordinates":[40.730610, -73.935242]}};
     });

     exp.save(function(err,doc){
       console.log("done");

     });

MongoDB-保存到MongoDB后

{ "_id" : ObjectId("57faa6b5a005aa179276d25d"),"loc" : { "_id" :     ObjectId("57faa6b5a005aa179276d25e"), "coordinates" : [ 0, 0 ], "type" : "Point" }}

模式

var geoSchema = new mongoose.Schema({
    type: {
      type: String,
      enum: 'Point',
      default: 'Point'
    },
    coordinates: {
      type: [Number],
      default: [0, 0]
    }
});

如何保存mongodb属性的数据。 id会自动生成:

       { "_id" : ObjectId("57faa6b5a005aa179276d25d"),
      "loc" : { "coordinates" : [ 40.730610, -73.935242 ], "type" : "Point" }}

2 个答案:

答案 0 :(得分:2)

您的架构中缺少loc

var geoSchema = new mongoose.Schema({
  loc: {
    type: Object,
    properties: {
      type: {
        type: String,
        enum: 'Point',
        default: 'Point'
      },
      coordinates: {
        type: [Number],
        default: [0, 0]
      }
    }
});

答案 1 :(得分:0)

这是不正确的

exp.loc = {"loc":{"type":"Point","coordinates":[40.730610, -73.935242]}};

必须

exp.loc = {"type":"Point","coordinates":[40.730610, -73.935242]};