chichi
chichi

Reputation: 3301

How to add GeoJson data with mongoose?

I am sending the object to create a user model.

"{ 
type: 'Point', 
coordinates: [ 25.2239771, 51.4993224 ] 
}"

And, here is the Mongoose Schema that I created.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserProfileSchema = new Schema(
  {
 
    userId: {
      type: String,
      // required: true,
      unique: true,
    },
    userFirstName: {
      type: String,
      // required: true,
    },
    userLastName: {
      type: String,
      // required: true,
    },
    userGender: {
      type: String,
      // required: true,
    },
    
    userCoordinates: {
      type: {
        type: String,
        default: 'Point',
      },
      coordinates: {
        type: [Number],
        index: '2dsphere',
      },       
    },
  },
  { collection: 'userprofilemodels' }
);

module.exports = UserProfile = mongoose.model(
  'userprofilemodels',
  UserProfileSchema
);

This is the code that I am using to add geoJson type file. However, I am getting an error. I also tried to add index after the Schema has been defined

await new userProfileModel({
        userId,
        userFirstName,
        userLastName,
        userCoordinates,

      })
        .save()
        .then(() => {
          console.log('it worked!');
          res.send('worked!');
        })
        .catch((error) => {
          console.log('did not worl')
          // console.log(error);
        });

If I exclude userCoordinates, then it works. So, def my geoJson object is wrong. However, I have no clue where I have made mistakes.

Upvotes: 2

Views: 1088

Answers (2)

Luis Orbaiceta
Luis Orbaiceta

Reputation: 473

Mongoose supports GeoJSON objects indexing so first add the "2dsphere" index to the userCoordintes rather than to the coordinates within the object in order to make it work.

userCoordinates: {
      type: {
        type: String,
        default: 'Point',
      },
      coordinates: {
        type: [Number],
        default: undefined,
        required: true
      },
      index: '2dsphere'       
},

Make sure your userCoordinates looks something like this:

const userCoordinates = {
        type: "Point",
        coordinates: [coordinatesA, coordinatesB],
};

Upvotes: 1

tsamaya
tsamaya

Reputation: 396

Taken from the mongoose documentation it seems the GeoJSON Type mustn't be only a String.

here is the example with location as a GeoJSON type:

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

Upvotes: 1

Related Questions