我有两个收藏集,如下所示:
这是我的车辆架构
const VehicleSchema = new schema({
user: {
type: schema.Types.ObjectId,
ref: "users"
},
name: {
type: String,
required: true
},
brand: {
type: String,
required: true
},
plate: {
type: String,
required: true
},
IMEI: {
type: String,
required: true
}
});
这是我的Trip模式
const TripSchema = new schema({
date: {
type: Date,
default: Date.now
},
IMEI: String,
data: [
{
lat: String,
lon: String
}
]
});
出行和车辆模式共享密钥IMEI,因此,当用户登录后,我想根据IMEI编号获取行程,解决此问题的最有效方法是什么?看一下我的路由器
router.get(
"/",
passport.authenticate("jwt", { session: false }),
(req, res) => {
Vehicles.find({ user: req.user.id }).then(vehicles => {
if (!vehicles) {
return res.json({ error: "you do not have any vehicles yet" });
}
Trips.find().then(trips => {
// ??
});
});
}
);
答案 0 :(得分:0)
您只需在行车时做$lookup并向左走join
:
db.vechicles.aggregate([
{
$lookup:
{
from: "trips",
localField: "IMEI",
foreignField: "IMEI",
as: "trips"
}
}
])
这一次就能为您带来想要的东西。
请注意,这在mongodb版本 3.2 +
中可用