In NodeJS I receive from Postman an object like:
sysData: {
status: 'active'
}
This needs to be dynamically converted to dot notation like
{ 'sysData.status': 'active' }
so I can do a find with Mongoose.
The object can change. How do I convert this dynamically?
In Postman I have created a Query Params following sysData.status, however, I don’t receive this in NodeJS. When I create a Query params following SysData[status] I receive this in NodeJS in object literal notation, which in my opinion I can’t use for Mongoose. So I need to convert this. Because the Query params can change, this needs to be done dynamically.
Or is there another way to resolve this?
2
Answers
You can use the
object
literalsysData: { status: 'active' }
to do afind()
on aModel
directly instead of first converting to dot notation before making queries. Mongoose will convert to dot notation internally before querying the database server.Problem:
Given an object passed from postman of:
When used in a mongoose query like so:
It will match this document:
But not this document:
The reason this happens is because when your query object is defined like so:
MongoDB will look for an exact match for
sysData
. The implications are that if you have another key in thesysData
object in your database (e.g.cores: 4
) then there won’t be an exact match.However, when you define your query object like this:
MongoDB will find both documents above because the query is only looking for a document where the
sysData.status
object has a value ofactive
. All other keys are irrelevant.Solution:
There are many ways to transform your postman object into the desired format. One way could be by using
Object.entries()
withObject.keys
andObject.values()
like so: