Skip to content

Dynamic key in MongoDB Node.js Native API

Learn how a key can be dynamic in a MongoDB Node.js native API.

  let tree = await db
        .collection("user_tree")
        .findOne({ userId: "john122" });

In the above code snippet, user_tree is queried using userId. But what if userId is dynamic i.e instead of userId we can use employeeId. To achieve this we can use a variable as a property name in an object literal by wrapping it in square brackets, like the example below.

let id="userId",idValue=req.body.userId;

if(userType && userType == "employee") {
        id="employeeId";
        idValue=req.body.employeeId;
      }

  let tree = await db
        .collection("user_tree")
        .findOne({ [id]: idValue });

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.