How to Define Object in Array in Mongoose Schema
Last Updated :
04 Apr, 2024
Mongoose schemas play an important role in defining the structure and properties of MongoDB collections which ensures consistency and validation of data.
This article focuses on understanding Mongoose schemas and provides a detailed guide on correctly defining an object in an array in a Mongoose schema with a 2D geo index.
How To Define Object In Array In Mongoose Schema Correctly With 2D Geo Index?
To define an object in an array in a Mongoose schema correctly with a 2D geo index, follow these below steps:
Step 1: Define the Schema
To start, let’s define a Mongoose schema with an array field containing objects representing locations with latitude and longitude coordinates. We’ll also add a 2D geo index to the coordinates field.
const mongoose = require('mongoose');
// Define a sub-schema for the objects in the array
const locationSchema = new mongoose.Schema({
name: String,
coordinates: {
type: { type: String, default: 'Point' }, // Set the type to 'Point' by default
coordinates: { type: [Number], required: true } // Array containing longitude and latitude values
}
});
// Define the main schema with the array field using the sub-schema
const schema = new mongoose.Schema({
locations: [locationSchema] // Array field containing objects with name and coordinates
});
// Add a 2D geo index to the coordinates field
schema.index({ 'locations.coordinates': '2dsphere' });
// Create a Mongoose model based on the schema
const LocationModel = mongoose.model('Location', schema);
Explanation: In this schema, locations
is an array containing objects with name
and coordinates
fields. The coordinates
field uses the GeoJSON format, where the type
is set to '
Point
'
and the coordinates
array contains the latitude and longitude values.
Step 2: Usage Example
Now that we have our schema and model defined, let’s use it to store and query locations with 2D geo indexing.
// Create a new location document
const location = new LocationModel({
locations: [
{ name: 'Location 1', coordinates: [-73.935242, 40.73061] }, // Location 1 with coordinates
{ name: 'Location 2', coordinates: [-122.419418, 37.774929] } // Location 2 with coordinates
]
});
// Save the document to the database
location.save();
// Query locations near a specific set of coordinates
LocationModel.find({
'locations.coordinates': {
$near: {
$geometry: { type: 'Point', coordinates: [-73.935242, 40.73061] }, // Coordinates for query
$maxDistance: 10000 // 10 kilometers maximum distance
}
}
}).exec((err, result) => {
if (err) {
console.error(err);
return;
}
console.log(result); // Output the query result
});
Explanation: In the above code we creates a new document location
with an array of locations, each containing a name and coordinates. It then saves this document to the database.
Afterward, it queries the LocationModel
to find locations near a specific set of coordinates, using a 10-kilometer radius for the query. The result of the query is display on console.
Benefits of 2D Geo Index
- Efficient Spatial Queries: With a 2D geo index, spatial queries become faster as MongoDB optimizes the search based on the indexed spatial data.
- Location-based Services: Applications can take advantage of spatial indexing to find nearby users or places, essential for location-based services.
- Geospatial Aggregation: MongoDB’s aggregation framework allows for complex analysis of geospatial data, facilitating operations like distance calculation, point clustering, or data aggregation within specific regions.
Conclusion
Overall, Understanidng Mongoose schema design with 2D geo indexing allow developers to build scalable, high-performance applications that can handle spatial data efficiently. It is essential for developers to working on applications that require geospatial functionality. By following the guidelines provided in this article, developers can efficiently define and manage geospatial data in MongoDB using Mongoose schemas.
Share your thoughts in the comments
Please Login to comment...