$$ lookup无法按预期方式打印答案,加入两个集合后显示空数组
[基本上,我在后端中创建了一个通知api,在那里我将使用查找来加入2个集合。 UserInfo集合应该显示sendInfo类型的数组,如果我正在将sendInfo作为空数组,则应该在其中进行点赞。请帮助
router.get("/notifications", auth, async (req, res) => {
try {
// const id=req.user._id;
let result = await UserInfo.aggregate([
{
$match: {
_id: req.user._id
}
},
{
$lookup: {
from: "sendlikecoffees",
localField: "_id",
foreignField: "receiverId",
as: "sendInfo"
}
}
]);
if (result) {
return res.status(200).json({
Body: result
});
}
} catch (e) {
console.log(e);
return res.status(500).json({
Body: "NETWORK_ERROR"
});
}
});
回答如下:您可以使用ObjectId。
const ObjectId = require('mongodb').ObjectId;
router.get("/notifications", auth, async (req, res) => {
try {
// const id=req.user._id;
let result = await UserInfo.aggregate([
{
$match: {
_id: ObjectId(req.user._id)
}
},
{
$lookup: {
from: "sendlikecoffees",
localField: "_id",
foreignField: "receiverId",
as: "sendInfo"
}
}
]);
if (result) {
return res.status(200).json({
Body: result
});
}
} catch (e) {
console.log(e);
return res.status(500).json({
Body: "NETWORK_ERROR"
});
}
});