我有一个节点/快速服务器。由于猫鼬,我已经连接到mongo数据库。我创建了一个带有位置字段的架构,并为其添加了索引。执行聚合时,mongo声称:
$ geoNear需要2d或2dsphere索引
这是我的代码:
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);
以下是汇总:
User.aggregate([
{$geoNear: {
near: { type: "Point", coordinates: location },
distanceField: "dist.calculated",
maxDistance,
}},
{$match: {
age: { $gte: minAge, $lte: maxAge },
}},
]).exec((_, data) => res.json({ data })
);
这是猫鼬的初始化:
// 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));
这有什么问题?