对对象展开的猫鼬聚合查找不起作用

时间:2019-07-24 08:17:29

标签: node.js mongodb mongoose aggregation-framework

我试图在显示用户某些结果的同时从问题文档中查找。用户模式中存在一个名称为questionAnswer且类型为array的字段。我也正在展开数组领域,但只重提了问题,但回答了领域。我做错了什么,请指导我。

这是我的userSchema:-

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'
        },

    ]
}

2 个答案:

答案 0 :(得分:0)

好吧,_id$lookup一起使用存在一些问题。因此,您可以使用以下示例。它使用猫鼬的填充功能。

const mongoose = require("mongoose")
const Schema = mongoose.Schema
const util = require('util')
// util is only used to see a well structured result in console. Else unnecesary
mongoose.connect('mongodb://localhost/stackoverflow', {useNewUrlParser: true});

const questionAnswerSchema = new Schema({
    question: {
        type: mongoose.Schema.ObjectId,
        ref: 'question',
        required: true
    },
    answer: {
        type: String,
        required: true
    },
});

const userSchema =  new Schema({
    name: {
        type: String,
        required: true
    },
    phoneNo: {
        type: String,
        required: true
    },
    questionAnswer: {
        type: [questionAnswerSchema]
    }
});


const questionFields = new Schema({
    title: {
        type: String,
        required: true
    },
    questionType: {
        type: String,
        required: true
    },
    sampleAnswer: {
        type: String,
        required: true
    }
});

const userModel = mongoose.model("user", userSchema)
const questionModel = mongoose.model("question", questionFields)

// Uncomment Insert section and Comment the find section to insert test docs.
// And, keep it current state to fetch results only

// Insert section :
// new questionModel({
//     title: "question title 1",
//     questionType: "type 1",
//     sampleAnswer: "answer 1"
// }).save().then(result => {
//     return new userModel({
//         name: "joker",
//         phoneNo: "999999999",
//         questionAnswer: [
//             {
//                 question: result._id,
//                 answer: "internal answer"
//             }
//         ]
//     }).save()

// }).then((result)=>{
//     console.log("save result", result)
// }).catch(err => {
//     console.log("err",err)
// })

// Find Section
userModel
    .findOne({ name: "joker" })
    .populate("questionAnswer.question","-_id") // may not pass "-_id" as an argument it's here just to hide _id from result
    .then(result => {
        console.log(util.inspect(result, false, null, true /* enable colors */))
    }).catch(err => {
        console.log("err", err)
    })

答案 1 :(得分:0)

您需要在聚合管道中添加更多过滤器。以下是对模型的完整汇总查询。希望对您有帮助!


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
      }
    },
])