我正在尝试从问题文档中查找,同时显示用户的一些结果。用户模式中有一个名为 QuestionAnswer 且类型为数组的字段。我也取消了数组字段,但只返回问题但回答字段。我做错了什么请指导我。
这是我的用户架构:-
let userSchema = new Schema({
name: {
type: String
required: true
}
phoneNo: {
type: String
required: true
}
questionAnswer: {
type: [questionAnswerSchema]
}
});
这是我的问题AnswerSchema
let questionAnswerSchema = new Schema({
question: {
type: Schema.Types.ObjectId,
ref: 'Question',
required: true
},
answer: {
type: String,
required: true
},
});
我的问题架构:-
let questionFields = new Schema({
title: {
type: String,
required: true,
},
questionType: {
type: String,
required: true,
},
sampleAnswer: {
type: String,
required: true,
}
});
和我的查询:-
let recommendationList = await userModel.aggregate([
{
$unwind: {
path: '$questionAnswer',
preserveNullAndEmptyArrays: true
}
},
{
$lookup: {
from: 'questions',
localField: 'questionAnswer.question',
foreignField: '_id',
as: 'questionAnswer'
}
},
])
我想要这样的预期输出
{
name: 'foo',
phoneNo: '1234567890'
questionAnswer: [
{
question: {
title: 'This is the first question'
questionType: 'longQuestion'
sampleAnswer: 'this is dummy sample answer'
}
answer: 'this is my first actual answer'
},
{
question: {
title: 'This is the second question'
questionType: 'shortQuestion'
sampleAnswer: 'this is dummy sample answer'
}
answer: 'this is my second actual answer'
},
]
}
最佳答案
您需要在聚合管道中添加更多过滤器。以下是模型的完整聚合查询。希望对您有帮助!
let recommendationList = await userModel.aggregate([
{
$unwind: unwindQuestion
},
{
$lookup: questionLookup
},
{
$unwind: '$datingQuestionAnswer.question'
},
{
$addFields: {
datingQuestionAnswer: {
$mergeObjects: ['$datingQuestionAnswer', '$datingQuestionAnswer']
}
}
},
{
$group: {
_id: '$_id',
datingQuestionAnswer: { $push: '$datingQuestionAnswer' },
}
},
{
$project: {
_id: 1,
datingQuestionAnswer: 1,
pageNo: 1
}
},
])
关于node.js - Mongoose 在对象展开字段上的聚合查找不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57178303/