0

Below is the schema. i want to get the answers as per matched qid, but i am getting all the answers in the answers array. i have tried almost all the queries but not able to understand why is this happening, if you could give link to other article that will be helpful too.

const id = req.params.id;
    
    Channel.findOne({answer: {qid: {$in: [id]}}})  
    .then(result => { 
        console.log(result);
        // let userAnswer;
        // userAnswer = result.answer.map(i => {
        //     return {userId: i.userId , userName: i.userId.name, answer: i.answer}
        // });
        // res.json({ans: userAnswer, question: result.content});  
    })
    .catch(err => {
        console.log(err);
    }); 





const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    const channelSchema = new Schema({
        name: {
            type: String,
            required: true
        },
        category: {
            type: String,
            required: true
        },
        creator: {
            type: String,
            required: true
        },
        subscribers: [{type: mongoose.Types.ObjectId, required: true, ref: 'User'}],
        content: {
            question: [{
                title: {type: String, required: true},
                userId: {type: mongoose.Types.ObjectId, required: true, ref: 'User'}
            }]
        },
        answer: [{
            answer: {type: String, required: true},
            qid: {type: mongoose.Types.ObjectId, required: true},
            userId: {type: mongoose.Types.ObjectId, required: true, ref: 'User'}
        }]
    });
    
    const model = mongoose.model('Channel', channelSchema);
    
    module.exports = model;
devesh
  • 111
  • 2
  • 11
  • 1
    Does this answer your question? [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) that's what you're looking for, using either `$elemMatch` or `$filter` is fine but you need to be sure input type does match with type in DB.. – whoami - fakeFaceTrueSoul Jun 22 '20 at 18:28
  • no, it's only give me single matched item. – devesh Jun 22 '20 at 18:37
  • what have you tried ? If you use ‘$elemMatch’ you would get only one element (first matched in array) use ‘$filter’ with projection.. – whoami - fakeFaceTrueSoul Jun 22 '20 at 18:42
  • this gives me null array ```{$project:{_id: 0, answers: {$filter: {input: "$answer", as: "ans", cond: {$eq: ["$$ans.qid", id]}}}}}``` – devesh Jun 22 '20 at 19:29
  • 1
    `qid` in DB is `ObjectId()`, can you print and give me input `id` ! Both types should match !! Do you mean `null array` empty array ? – whoami - fakeFaceTrueSoul Jun 22 '20 at 20:11
  • yes id is string type. – devesh Jun 22 '20 at 20:16

1 Answers1

0
const id = req.params.id;
    
    return Channel.findOne({answer: {qid: {$in: [id]}}})  
    .then(snapshot => { 
        const results = [];
                    snapshot.forEach(doc => {
                        results.push({
                            id: doc.id,
                            data: doc.data()
                        });
                    });

                    return results;
                })
          
    })
    .catch(err => {
        console.log(err);
    }); 

This is the way when you are going to fetch one array record. Not tested, only to show you how to get single record from collection

Krishan Kumar
  • 394
  • 4
  • 13