我有两种不同的猫鼬模型,我想查询一种,并根据特定属性与另一种进行汇总。 我的第一个文件是:
const streetSchema = new Schema({
streetName: {type: String,require:true},
})
const areaSchema = new Schema({
description :{type:String,require:true,unique:true},
streets: [areaSchema]
});
module.exports = mongoose.model('AreaModel', areaSchema)
我的第二个文档是:
const locationSchema = new Schema({
streetId: {type: Schema.Types.ObjectId},
loc: {
type: {type: String},
coordinates: [Number],
}
});
locationSchema.index({"loc":"2dsphere"});
module.exports = mongoose.model('LocationModel', locationSchema)
locationchema上的streetId属性引用了streetSchema上的_id。
在我的数据库中,我的areaModel数据将是:
{
"_id" : ObjectId("5c16d26de6cbea23a0393b45"),
"__v" : 0,
"description" : "Area A",
"streets" : [
{
"_id" : ObjectId("5c16d3a8e6cbea23a0393b48"),
"streetName" : "Wilson"
},
{
"_id" : ObjectId("5c16d3bce6cbea23a0393b49"),
"streetName" : "Trafalgar"
},
{
"_id" : ObjectId("5c16d3cde6cbea23a0393b4a"),
"streetName" : "Pres. Lincoln"
},
{
"_id" : ObjectId("5c16d3e6e6cbea23a0393b4b"),
"streetName" : "Waterloo"
}
]
}
在我的数据库中,locationModel的数据将是:
{
"_id" : ObjectId("5c176e1178e6d72bbcc6ecac"),
"__v" : 0,
"loc" : {
"coordinates" : [
41.536719,
-8.628619
],
"type" : "Point"
},
"streetId" : ObjectId("5c16d3a8e6cbea23a0393b48"),
}
/* 2 */
{
"_id" : ObjectId("5c176e7098ea721018ba9d43"),
"__v" : 0,
"loc" : {
"coordinates" : [
41.536581,
-8.628643
],
"type" : "Point"
},
"streetId" : ObjectId("5c16d3a8e6cbea23a0393b49")
}
我想做的是试图找到GPS坐标附近的所有位置,为此,我正在使用$ near,并且正在获取一系列位置,但是因为这些位置上的某些streetId是相同的,因为这些位置属于同一条街道。 因此,我试图获取唯一的streetId,以查询AreaModel以获得该ID的streetName并将其添加到locations数组中。
到目前为止,我有这个:
exports.get_locations = async (req, res, next) => {
let maxDistance= 500;
try {
const location = await Location.find(
{
loc: {
$near: {
$geometry: {
type: "Point",
coordinates: [req.params.long, req.params.lat]
},
$maxDistance: maxDistance
}
}
},{_id:0,'__v':0}
)
// after this step i have my locations based on distance query
// here i am getting my unique streetID
const unique = [...new Set(location.map(item => item.streetId))];
// I AM BLOCKING HERE
res.send(locations);
} catch (error) {
next(error);
}
}
我最终期望的结果是:
{
"_id" : ObjectId("5c176e1178e6d72bbcc6ecac"),
"__v" : 0,
"loc" : {
"coordinates" : [
41.536719,
-8.628619
],
"type" : "Point"
},
"streetId" : ObjectId("5c16d3a8e6cbea23a0393b48"),
"streetName": "Winson" // STREET NAME HAS BEEN ADDED HERE
}
/* 2 */
{
"_id" : ObjectId("5c176e7098ea721018ba9d43"),
"__v" : 0,
"loc" : {
"coordinates" : [
41.536581,
-8.628643
],
"type" : "Point"
},
"streetId" : ObjectId("5c16d3a8e6cbea23a0393b49")
"streetName": "Trafalgar" // NAME HAS BEEN ADDED HERE
}
是否可以通过$ project,$ lookup或其他方法使用更优雅的方式来获得结果?