iAmRoot iAmRoot - 3 years ago 201
Javascript Question

Search and filter data in Mongo DB using mongoose



var questionSchema = new Schema({
category: { name:
{
type: String,
lowercase: true,
required: [true, 'Category is a required field']
},
question:[
{
q: {
type: String,
lowercase: true

},
options: {
option1:{
type: String,
lowercase: true

},
option2:{
type: String,
lowercase: true
]
},
option3:{
type: String,
lowercase: true

},
option4:{
type: String,
lowercase: true

},
},
ans: {
type: String,
lowercase: true

},
level:{
type: String,
lowercase: true

}

}

]
},


},
{
strict: true,
runSettersOnQuery: true,
timestamps: {
createdAt: 'created', updatedAt: 'updated'
}
});





This is my question schema. I am trying to get all the questions of a particular category. Till now I have tried this ---



function (req,res,next) {
console.log(req.params.qcategory);
Question.find({
category:{
name: req.params.qcategory,
}
},'', function (err,data) {
if (err) {
err.status = 406;
return next(err);
}
console.log(data);
return res.status(201).json({
message: ' success.',data:data
})
})
};





In req.params.qcategory it contains the name of the category like 'programming' for instance.
But it returned me an empty array. **PS. There are questions of programming category in my DB. Then What am i doing wrong ???

Also is there a way to first check what category a question is and then add to the question array inside that particular category. I don't want to add questions with categories again and again instead i want to check if that category already exists in the database and push the question inside the array of that question category. For instance if a question is of 'programming' category and in the database there is already a question which is of again a 'programming' category then push the question inside the array of programming category.

If my questions are not clear then please comment I will respond quickly.

Answer Source

Try this, Not tested

function (req,res,next) {
console.log(req.params.qcategory);
Question.find({
    "category.name": req.params.qcategory,}
 , function (err,data) {
    if (err) {
        err.status = 406;
        return next(err);
    }
    console.log(data);
    return res.status(201).json({
        message: ' success.',data:data
    })
})
};

Replace the {category:{name:req.params.qcategory}} with {"category.name":req.params.qcategory}.

read more on mongodb's Query Embedded Documents https://docs.mongodb.com/.../method/db.collection.find/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download