mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Multidimensional Array retrieval fails - flattening the array

Open cfergus opened this issue 12 years ago • 3 comments

I have a mongoose schema containing a multi-dimensional array. This is part of a geojson data structure. The data saves properly, I can view it directly in Mongodb, and it looks like I expect. When it is retrieved, mongoose flattens the array to be a single-dimensional array, which is undesired behavior.

I am using: mongoose version 3.8.8 node 0.10.26 mongodb 2.4.0

Code below to recreate the problem.

/* Schema */
var mongoose = require('mongoose')
  , Schema = mongoose.Schema
var ObjectId = Schema.ObjectId;

var AreaSchema = new Schema({
  geometry : {    
    type : { type : String, default : 'Polygon' },
    coordinates: []
  } 
})

mongoose.model('Area', AreaSchema)
var Area = mongoose.model('Area')



/* Mongo connect */

var connect = function () {
  var options = { 
    server: { socketOptions: { keepAlive: 1 }}
  }
  mongoose.connect('mongodb://localhost/flatten_example', options)
}
connect()

// Error handler
mongoose.connection.on('error', function (err) {
  console.log(err)
})



/* Test case */
var my_area = new Area(
{"geometry" : 
  { "coordinates" : [
    [
      [-77.38494873046875,39.56017699732935],[-77.4261474609375,    39.66068502219227]
    ]
  ], 
  "type" : "Polygon" }}
)

my_area.save( function (err) {

  Area.findById( my_area._id, function (err, result) {
    console.dir( result.geometry.coordinates );

    /*
    * Result is a one-dimensional array, flattened from the original
    * [-77.38494873046875,39.56017699732935,-77.4261474609375,39.6606850221922]
    * 
    * Note that it is properly stored in mongodb as a multi-dimensional array
    */
  })
})

Related discussion here : https://groups.google.com/forum/#!topic/mongoose-orm/vgh5jFzOfFU

cfergus avatar Apr 05 '14 14:04 cfergus

Also, below is code to confirm that 'plain' mongo retrieves the data properly.

var MongoClient = require('mongodb').MongoClient

MongoClient.connect('mongodb://127.0.0.1:27017/flatten_example', function(err, db) {
  if(err) throw err;

  var collection = db.collection('areas');

  // Locate all the entries using find
  collection.find().toArray(function(err, results) {

    console.dir( results[0].geometry.coordinates )

      /*
      * Result below is expected
      * [ [ [ -77.4261474609375, 39.66068502219227 ],
      * [ -77.43026733398438, 39.56864645674724 ],
      * [ -77.38494873046875, 39.56017699732935 ],
      * [ -77.4261474609375, 39.66068502219227 ] ] ]
      */

    db.close();
  });
})

cfergus avatar Apr 05 '14 14:04 cfergus

+1 same issue here

mradamh avatar Jul 10 '14 17:07 mradamh

Fix will be in next version. FWIW it was only an issue with mongoose's stringifying code, JSON.stringify(results[0].geometry.coordinates) would give you the proper output.

vkarpov15 avatar Jul 15 '14 19:07 vkarpov15