简体   繁体   中英

Sending array to populate geospatial field using Mongoose + NodeJS

I'm trying to save a geospatial array into a Schema. Here is my Schema (I'm using Moongose + Express + NodeJS):

var Route = new schema({
    route: String,
    time: Number,
    distance: Number,
    geo: {type: [Number], index: '2d'},
    created: { type: Date, default: Date.now }
}, {collection: 'route'});
var routeModel = mongoose.model('Route', Route);

And here is an example of the data I'm sending to populate an instance of that schema:

{ 
    distance: 6.899893863658173,
    geo:[ [13.695901, -89.24937], [13.706500876975248, -89.24967010761316], 
          [13.711430396814366, -89.2561502488519] ],
    route: "Running route",
    time: 31
}

First noob question is: is it possible to do what I'm doing? sending an array of arrays in geo?

And here is how I save the data:

socket.on('new_route', function (data){
   var route = new routeModel();
   route.route = data.route;
   route.time = data.time;
   route.distance = data.distance;
   route.geo = data.geo;
   route.save(function(err) {
       if (err) throw err;
       socket.emit("route_saved", {mensaje: "Well done!"});
       app.listen(8080);
   });  
});

If I send and empty array on geo, all works fine. However, I'm getting the following error

"Cast to number failed for "13.695901, -89.24937, 13.706500876975248, -89.24967010761316..." at path "geo".

whenever I send an array (like the one posted above) on "geo".

So second question, any ideas on why I'm getting my array threated like a big string?

Mongoose doesn't support arrays of arrays of any type ( [[Number]] ). It may be supported in the future .

If your use case requires this schema, use a Mixed type which allows ad-hoc structures but provides no change tracking or casting.

new Schema({ geo: { type: Schema.Types.Mixed, index: '2d' }})

As for arrays being treated as a big string, mongoose converts the invalid argument to a string and what you observe is an artifact of how javascript converts arrays to strings.

var a = [3,4,5]
console.log(String(a)) // '3,4,5'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM