【发布时间】:2019-12-02 08:02:33
【问题描述】:
我正在尝试从问题文档中查找,同时显示一些用户的结果。用户模式中有一个名为 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'
},
]
}
【问题讨论】:
-
questionsSchema 是什么样子的? @阿西夫 -
@PrasantaBose 我已经用问题模式更新了我的问题。请看一下
-
见下面我的回答。 @阿西夫
-
我不确定你是如何插入数据的所以,提供了一个插入代码。如果数据插入正确,可能是不必要的。 @阿西夫
标签: node.js mongodb mongoose aggregation-framework