Mongoose combines two queries for one collection

I am trying to make a query to search for documents depending on another document in the same collection as below.

The first finds the user, and the second finds the data using the received user data. But I want to do this with a single query, for example, join SQL

This is a circuit

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()
}

});

// requests

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 },
    });
});

Is there a way to do this with just one request? Thank.

+4
source share
1 answer

yes there is a way you can do it

    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
    });
+2
source

Source: https://habr.com/ru/post/1694019/


All Articles