Embedded document query not working!

So I was using this way to find my the documents and it was working perfectly fine:
As an example:
const sessions = await safeerSessionModel.find({
safeer: {
id: safeer.id,
name: safeer.name,
},
});
As of today it is not working, when I run the query it returns 0 documents

but when I change it to following
const sessions = await safeerSessionModel.find({
“safeer.id”: safeer.id,
“safeer.name”: safeer.name,
},
});
it starts working again and shows me the list of expected documents.
I am unable to figure out why it this happening

I do not know if it is your case with mongoose, but 2 objects are equals if they have the same fields and values in the same order. And this has been like that since how long I remember. Object c:{a:1,b:2} is not equal to c:{b:2,a:1} because the fields b and a are not in the same order. Also, object c:{a:1,b:2} is not equal to c:{a:1,b:2,d:3} are not equals because of the extra field.

Perhaps, your model has change and new fields are in safeer or the field order has been altered. Or perhaps some data has been inserted or updated without the model, with a different order or with extra fields. The second query works because the equality is field equality rather than object equality.

Starting collection

{  _id: 0,  safeer: {    id: 1,    name: 2  }}
{  _id: 3,  safeer: {    name: 2,    id: 1  }}
{  _id: 0,  safeer: {    id: 1,    name: 2, x: 4  }}

Using object equality

/* looking for object safeer equals to id:1,name:2 */
c.find( { safeer : { id :1 , name : 2}})
/* only object with same fields and same order is returned */
{  _id: 0,  safeer: {    id: 1,    name: 2  }}

Using field value equality

c.find( { "safeer.id" :1 , "safeer.name" : 2})
/* all documents are returned because they all have safeer.id:1 and safeer.name:2*/
{  _id: 0,  safeer: {    id: 1,    name: 2  }}
{  _id: 3,  safeer: {    name: 2,    id: 1  }}
{  _id: 0,  safeer: {    id: 1,    name: 2, x: 4  }}

So the difference in result you see has always been like that, at least in plain mongo. You notice the difference now because your model has changed or your data has changed. I wrote in plain mongo, because you should not rule out that may be mongoose introduced a breaking change where using object equality is mapped differently from mongoose to mongo. May be mongoose reorder the fields so that they are always consitent.

in my model the field safeer is of type object, I have not given fixed key value pairs to it,

example: something = new mongoose.Schema({
safeer: Object,
})

but before this object used to store only 2 values, recently I added new value to it example phone no, only the new documents are having the safeer object with 3 key val pairs, old ones only have 2.
Can this cause an issue ?

Yes, as I already mentioned

Thanks, I have updated it, works now.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.