我正在尝试根据以下相同集合中的另一个文档进行查询以查找文档。

第一个找到用户,第二个通过使用收到的用户数据找到数据。但我想用一个查询来做到这一点,比如加入 SQL

这是架构

var ConnectionSchema = new Schema({
socketId: {
    type: String,
    require: true
},
location: {
    type: [Number],
    index: '2dsphere'
},
user: { type: Schema.ObjectId, ref: "User" },
date: {
    type: Date,
    require: true,
    default: new Date()
}

});

//查询
return mongoose.model("Connection").findOne({ user: userId }).populate("user").then(usr => {
    return mongoose.model("Connection").find({
        location: {
            $near: {
                $maxDistance: config.searchDistance,
                $geometry: { type: Number, coordinates: usr.location }
            }
        },
        user: { $ne: userId },
    });
});

有没有办法通过一个查询来做到这一点?
谢谢。

最佳答案

是的,有一种方法可以这样做

    return mongoose.model("Connection").findOne({ user: userId })
.populate("user" ,
        match : {$and : [{location: {
            $near: {
                $maxDistance: config.searchDistance,
                $geometry: { type: Number, coordinates: usr.location }
            }
          }},
           {user: { $ne: userId }}]})
        .then(usr => {
        // perform your action
    });

10-06 12:58
查看更多