skip to Main Content

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


  1. You can use the object literal sysData: { status: 'active' } to do a find() on a Model directly instead of first converting to dot notation before making queries. Mongoose will convert to dot notation internally before querying the database server.

    query = { sysData: { status: 'active' } }
    Model.find(query) /*[mongoose-docs]*/ /* <—— query will be used as filter parameter. */
    Login or Signup to reply.
  2. Problem:

    Given an object passed from postman of:

    { sysData: { status: 'active'} }
    

    When used in a mongoose query like so:

    Model.find({ sysData: { status: 'active'} })
    

    It will match this document:

    //Document 1
    {
       name: 'bob',
       age: 21,
       sysData: { status: 'active' }
    }
    

    But not this document:

    //Document 2
    {
       name: 'sally',
       age: 60,
       sysData: { status: 'active', cores: 4 }
    }
    

    The reason this happens is because when your query object is defined like so:

    { sysData: { status: 'active'} }
    

    MongoDB will look for an exact match for sysData. The implications are that if you have another key in the sysData 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:

    { 'sysData.status': 'active' }
    

    MongoDB will find both documents above because the query is only looking for a document where the sysData.status object has a value of active. 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() with Object.keys and Object.values() like so:

    const postman = { sysData: { status: 'active'} };
    let query = {};
    const key = `${Object.keys(postman)[0]}.${Object.keys(Object.entries(postman)[0][1])[0]}`;
    const value = Object.values(Object.entries(postman)[0][1])[0];
    query[key] = value;
    Model.find(query);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search