Last active
March 3, 2023 17:02
-
-
Save itsabdessalam/d614e43618ec08ebd418666e5767ec66 to your computer and use it in GitHub Desktop.
Store mongoose model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mongoose = require("mongoose"); | |
const Schema = mongoose.Schema; | |
// On définit le schéma du Store | |
const StoreSchema = new Schema({ | |
name: { | |
type: String, | |
required: true | |
}, | |
address: { | |
street: String, | |
number: Number, | |
city: { | |
type: String, | |
required: true | |
}, | |
zipCode: { | |
type: String, | |
required: true | |
}, | |
location: { | |
type: { | |
type: String, | |
enum: ["Point"], | |
default: "Point" | |
}, | |
coordinates: { | |
type: [Number], | |
default: [0, 0] | |
} | |
} | |
}, | |
createdOn: { type: Date, default: Date.now }, | |
updatedOn: { type: Date, default: Date.now } | |
}); | |
// On crée l'index pour $geoNear | |
StoreSchema.index({ "address.location": "2dsphere" }); | |
// On définit des méthodes statics propres au schéma | |
// On récupère tous les stores | |
StoreSchema.statics.findAll = function() { | |
return this.find({}); | |
}; | |
// On récupère seulement les stores | |
// les plus proches | |
StoreSchema.statics.findByCoordinates = function(coordinates, maxDistance) { | |
return this.aggregate([ | |
{ | |
$geoNear: { | |
near: { | |
type: "Point", | |
coordinates: coordinates | |
}, | |
maxDistance: maxDistance, | |
distanceField: "dist.calculated", | |
spherical: true | |
} | |
} | |
]); | |
}; | |
module.exports = mongoose.model("Store", StoreSchema); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment