0

I am trying to query for records in my database but I am getting an empty array. I don't know what I am doing wrong? I have a feeling the issue could be my schema, here it is:

my schema

const QuizSchema = new Schema({

    question: {
        type:String,
        default:''
    },
    answers: [{
        type: {
            type: String,
            default:''
        },
        content: {
            type: String,
            default:''
        },
    }]
});

module.exports=Quiz=mongoose.model('quizes',QuizSchema,'quiz');

Here is the mongoose query

const Quiz = require('../../models/Quiz');

router.get('/',(req,res)=>{

Quiz.find({},null)
.then(data=>res.json(data))
.catch(err=>console.log(err))
});
module.exports = router;


And here is a sample JSON data

{
        "question": "What is a Mongoose ? ",
        "answers": [
            { "type": "Smart","content": "Animal" }, {"type": "Subpar", "content": "Software"}, { "type": "Confused", "content": "Poem" }]

    }


Would appreciate your assistance. Thanks in advance!

1
  • @Shubh Yes, i have tried without parameters, same empty array Commented Sep 12, 2019 at 10:35

2 Answers 2

1

<query>.then doesn't return the data. You should use <query>.exec().then to access the data returned by the query. So change your code to something like:

Quiz.find({},null)
.exec()
.then(data=>res.json(data))
.catch(err=>console.log(err))
});
module.exports = router;

Source: Mongoose docs

Sign up to request clarification or add additional context in comments.

3 Comments

@8SINS please add the logged response and the query you are using fetch the sample data.
router.get('/',(req,res)=>{ Quiz.find({},null) .exec() .then(data=>res.json(data)) .catch(err=>console.log(err)) }); I am testing with postman, and the reponse is 200 oK but with an empty array
Your Solution was correct! I just found out my mistake... I wasn't querying the right DB. thanks a lot
0

Modify Schema like this: Inside the array, field name like 'type' is not accepted.

const QuizSchema = new Schema({

    question: {
        type:String,
        default:''
    },
    answers: [{
        ans_type: { // CHANGE HERE
            type: String,
            default:''
        },
        content: {
            type: String,
            default:''
        },
    }]
});

module.exports=Quiz=mongoose.model('quizes',QuizSchema,'quiz');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.