我有这样的输出,但我想通过_id过滤事件数组,这与父对象_id相同。我想根据这种条件对其进行过滤。
[
{
"_id": "5cc45eb430aaba3cdc045dc0" ,
"word": "Pasta",
"translate": "Makarna",
"kind": "İsim",
"exampleSentence": "asljdalsd",
"__v": 0,
"events": [
{
"_id": "5cc45eb430aaba3cdc045dc0",
"createdAt": "2019-04-27T13:52:15.721Z",
"TenMinutesLater": "2019-04-27T13:52:25.721Z",
"OneWeekLater": "2019-05-04T13:52:15.721Z",
"OneMonthLater": "2019-05-27T13:52:15.721Z",
"FourMonthLater": "2019-08-27T13:52:15.721Z",
"__v": 0
},
{
"_id": "5cc45ee630aaba3cdc045dc1",
"createdAt": "2019-04-27T13:52:15.721Z",
"TenMinutesLater": "2019-04-27T13:52:25.721Z",
"OneWeekLater": "2019-05-04T13:52:15.721Z",
"OneMonthLater": "2019-05-27T13:52:15.721Z",
"FourMonthLater": "2019-08-27T13:52:15.721Z",
"__v": 0
}
]
}
]
我想过滤与父对象_id具有相同_id属性的事件数组。如何根据我的查询查询?
这是我的查询
Word.find({ _id: req.params.id }, (err, words) => {
if (err) {
console.log(err);
}
const uid = words.map(word => word._id);
console.log(req.params.id);
Word.aggregate([
{
$match: {
_id: {
$in: uid.map(function(id) {
return new mongoose.Types.ObjectId(id);
})
}
}
},
{
$lookup: {
from: "tests",
localField: "eventId",
foreignField: "_id.str",
as: "events"
}
}
])
.then(data => {
res.json(data);
})
.catch(err => {
throw err;
});
});
我想要这样的输出。如何使用父对象的_id对其进行过滤?
[
{
"_id": "5cc45eb430aaba3cdc045dc0" ,
"word": "Pasta",
"translate": "Makarna",
"kind": "İsim",
"exampleSentence": "asljdalsd",
"__v": 0,
"events": [
{
"_id": "5cc45eb430aaba3cdc045dc0",
"createdAt": "2019-04-27T13:52:15.721Z",
"TenMinutesLater": "2019-04-27T13:52:25.721Z",
"OneWeekLater": "2019-05-04T13:52:15.721Z",
"OneMonthLater": "2019-05-27T13:52:15.721Z",
"FourMonthLater": "2019-08-27T13:52:15.721Z",
"__v": 0
]
}
]
答案 0 :(得分:0)
谢谢您的回答,但我终于解决了这样的问题。它运行正常
Word.find({ _id: req.params.id }, (err, words) => {
if (err) {
console.log(err);
}
const uid = words.map(word => word._id);
Word.aggregate([
{
$match: {
_id: {
$in: uid.map(function(id) {
return mongoose.Types.ObjectId(id);
})
}
}
},
{
$lookup: {
from: "tests",
localField: "_id.str",
foreignField: "eventId",
as: "events"
}
},
{
$addFields: {
events: {
$filter: {
input: "$events",
as: "event",
cond: {
$eq: ["$$event._id", mongoose.Types.ObjectId(req.params.id)]
}
}
}
}
}
])
.then(data => {
res.json(data);
})
.catch(err => {
throw err;
});
});