Saturday, 13 June 2020

How to create a 2dsphere index in Mongoose?

Hello,I have a node/express server. I'm connected to a mongo database thanks to mongoose. I have created a schema with a location field and added an index to it. When performing an aggregation, mongo claims that$geoNear requires a 2d or 2dsphere indexHere is my code:const mongoose = require("mongoose"); const Schema = mongoose.Schema; const userSchema = new Schema( { username: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, age: {type: Number}, location: { type: { type: String, enum: ["Point"] }, coordinates: { type: [Number] }, }, }, { timestamps: true } ); userSchema.index({ age: 1, location: "2dsphere"}); module.exports = mongoose.model("User", userSchema); Here is the aggregation:User.aggregate([ {$geoNear: { near: { type: "Point", coordinates: location }, distanceField: "dist.calculated", maxDistance, }}, {$match: { age: { $gte: minAge, $lte: maxAge }, }}, ]).exec((_, data) => res.json({ data }) ); Here is the initialization of mongoose:// Connect to MongoDB and start server mongoose .set("useFindAndModify", false) .connect(process.env.MONGODB, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, autoIndex: false, }) .then(() => server.listen(process.env.PORT, () => console.log(`server is listening on ${process.env.PORT}!`) ) ) .catch((err) => console.log("error", err)); What is wrong with it?

Submitted June 13, 2020 at 07:15PM by MonsieurLeland

No comments:

Post a Comment