我正在尝试根据同一集合中的另一个文档进行查询以查找文档,如下所示。
第一个找到用户,第二个通过使用收到的用户数据找到数据。但是我想用一个查询来完成它,比如在 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
});
关于javascript - Mongoose 将两个查询合并为同一集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48937122/