0

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 index

Here 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?

DoneDeal0
  • 5,273
  • 13
  • 55
  • 114
  • Does this answer your question: https://stackoverflow.com/questions/59920729/index-is-not-getting-created-text-index-required-for-text-query-mongoose/59922531#59922531 ? – mickl Jun 13 '20 at 20:08
  • No. I added User.createIndexes() once mongoose initialization succeeds (in the then() ). I also tried to remove autoIndex: false (writing it is recommended in the official documentation though). I still have the error "MongoError: $geoNear requires a 2d or 2dsphere index, but none were found" – DoneDeal0 Jun 13 '20 at 20:36

0 Answers0