Search code examples
javascriptnode.jsmongodbmongoosesubdocument

Why is no document returned while querying a sub-doc in Mongoose?


I am running the following code:

var oid = new mongoose.Types.ObjectId(req.params.id);
req.query = {
    toId : {
        id: oid
    },
    deleted : false
};  
X.find(req.query,  function (err, docs){
    if(!err){   
        res.status(responses.ok.status).json(docs);
    }
    else{
        return next(errorHelper(err));
    }
}).select(visibleFields.X);

I would like to query the X model by its toId.id field. toId field is of type Y. Here are the model definitions:

var X = new Schema({
deleted: {
    type: Boolean, 
    required: true, 
    default: false
},      
toId: {
    type: entityId,
    required: true
}   
});

Y is just an object defined as:

var Y = {
id: {
    type: Schema.Types.ObjectId,
    required: true
},
entityName:{
    type: String,
    required: true,
    enum: entityTypeList
}
};

In my database, I have an entry like:

{
"_id" : ObjectId("55d1f4fddaea17d3e90a3c55"),

"toId" : {
    "id" : ObjectId("55dde27a0f6ff71b72dc7981"),
    "entity" : "user"
},

"deleted" : false

}

which should, by all means, satisfy my criteria.

However, the following query:

messages.find({ deleted: false, toId: { id: ObjectId("55dde27a0f6ff71b72dc7981") } }) { fields: { messageType: 1, toId: 1, timesOff: 1, role: 1, read: 1, productId: 1, participantId: 1, oldRole: 1, message: 1, memberId: 1, lessonId: 1, important: 1, fromId: 1, formerInstructorId: 1, timestamp: 1, changedFields: 1, bookerId: 1, assignedInstructorId: 1, accepted: 1, _id: 1 } }  

returns an empty list. Why is that happening?


Solution

  • Try a query like this:

    req.query = {
        "toId.id": oid,
        deleted : false
    };