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
        .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") {

  let tree = await db
        .findOne({ [id]: idValue });
See also  How to query an array in MongoDB?

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.