I have a MongoDB document in the following format. I can verify that it exists in MongoDB using Compass. I'm using TypeORM to make the query, not MondoDB.
{
_id: 'some id'
user: {
details: {
email: "[email protected]",
username: "testname"
},
status: 'active'
}
}
Is it possible to use TypeORM to find by, say, the email?
I've tried
const emailExists = await this.userRepo.findOneBy({
user: {
details: {
email: "[email protected]"
}
}
});
but emailExists
always returns null even though I can validate that it exists in MongoDB. I've tried other ways to find by email
using find
, findOne
, and more.
How do you find a matching value of a child property, like email
? Is there a better approach?
CodePudding user response:
MongoDB: Query on Nested Field
To specify a query condition on fields in an embedded/nested document, use dot notation.
- Example:
'field.nestedField'
When querying using dot notation:
The field and nested field must be inside quotation marks.
Applying in your code:
const emailExists = await this.userRepo.findOneBy({'user.details.email': '[email protected]'});
Reference:
Update: Looks TypeORM not work well with MongoDB, but you can try use $match
.
Example:
$match : { 'field.nestedField': nestedField }
Applying in your code:
this.userRepo.findOneBy({$match: { 'user.details.email': '[email protected]' }});
If not work maybe try to change TypeORM to Mongoose.