In Mongoose, defining GeoJSON fields for MongoDB primarily involves specifying appropriate GeoJSON data types within the schema. GeoJSON is a standard geographic data format that MongoDB natively supports, making it highly efficient and convenient to store geographical information in the database.
To define GeoJSON fields in a Mongoose schema, follow these steps:
1. Install and import the Mongoose library
First, ensure Mongoose is installed in your project and imported in your file.
javascriptconst mongoose = require('mongoose');
2. Create a Schema
In Mongoose, define a Schema to map the structure of your MongoDB collection. Within this Schema, specify one or more GeoJSON fields.
3. Define GeoJSON fields
In the Schema, use specific GeoJSON types such as Point, LineString, or Polygon. These types are typically defined under a field named geometry:
javascriptconst LocationSchema = new mongoose.Schema({ name: String, location: { type: { type: String, enum: ['Point', 'LineString', 'Polygon'], // GeoJSON type required: true }, coordinates: { type: [Number], // Longitude and latitude or more complex coordinate sets required: true } } });
4. Create a Model using the Schema
javascriptconst Location = mongoose.model('Location', LocationSchema);
5. Instantiate and use the Model
Create a new geographical location instance and save it to the database:
javascriptlet loc = new Location({ name: 'Central Park', location: { type: 'Point', coordinates: [-73.97, 40.77] } }); loc.save(function(err) { if (err) throw err; console.log('Geographical location saved successfully!'); });
Example
Consider a practical example where you need to store geographical information for cities. Each city can be represented by a point for its coordinates (longitude and latitude):
javascriptconst CitySchema = new mongoose.Schema({ name: String, position: { type: { type: String, default: 'Point', }, coordinates: { type: [Number], // [longitude, latitude] required: true } } }); const City = mongoose.model('City', CitySchema); let shanghai = new City({ name: 'Shanghai', position: { coordinates: [121.4737, 31.2304] } }); shanghai.save(function(err) { if (err) throw err; console.log('City geographical information saved.'); });
This approach enables you to effectively utilize GeoJSON fields in Mongoose, providing robust geographical data processing capabilities for your application.