8SINS
8SINS

Reputation: 461

How to fix mongoose query that returns empty array

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!

Upvotes: 0

Views: 66

Answers (2)

Binod Chaudhary
Binod Chaudhary

Reputation: 33

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');

Upvotes: 0

tbking
tbking

Reputation: 9116

<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

Upvotes: 1

Related Questions