Mongoose: Querying on Object ID type

Hello,

One of my collections contains a propertyId field that is defined as an ObjectId. I use the following query in a NodeJS environment with mongoose:

const propertyId = '6505ec11ae11d65c4bbb0727';
const ObjectId = require('mongoose').Types.ObjectId;
const objectId = new ObjectId(propertyId);
const results = await this.imageModel.find({ propertyId: objectId });

For some reason, the query returns an empty list of results even though I can confirm there are multiple documents with the given propertyId.

Am I missing something here? Why do queries not work on the ObjectId type with mongoose?

Thanks.
Luke

Hey @Lucas_Lind,

On first reading the question this appeared to be a query casting issue, but if you’ve already cast objectId to an ObjectId then this may not be the case.

Can you enable logging and verify that (a) the query that’s being sent to the server is correct and (b) the correct cluster/database/collection is being targeted? This should make it a lot easier to determine what’s going wrong.

Hey Alex, thanks for the quick reply.

I’ve enabled logging as you requested. I added an additional query to fetch an entry from ID to ensure that the server, cluster, and DB are correct. Log results:

Mongoose: images.findOne({ _id: ObjectId("65ad42687b060d6038177e45") }, {})
[DEBUG] Image label: EXTERIOR
Mongoose: images.find({ propertyId: '6578f033adc722b67624a271' }, {})
[DEBUG] Results: []

It seems like even though I’m making an explicit cast of the propertyId to an ObjectId, it’s still being registered as a string. Below is the exact code I used to get the above output:

mongoose.set('debug', true);

const imageId = '65ad42687b060d6038177e45';
const image = await this.imageModel.findById(imageId);
console.log('[DEBUG] Image label:', image.label);

const ObjectId = mongoose.Types.ObjectId; // import is out of view, but same as before
const results = await this.imageModel.find({ propertyId: new ObjectId(propertyId) });
console.log('[DEBUG] Results:', results);
return results;

Share your schema definitions. May be mongoose, is doing some type modification and overrides the fact that yo do pass an ObjectId.

@steevej great intuition. My schema definition had the propertyId field defined as a string instead of an ObjectId. This fixed the issue.

Thank you!!

1 Like

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