Find document using varying fields in MongoDB

In my project, there is a page in which the user can search logs created and may specify none or several values about said logs, such as creation date. However I don't currently know how to make this search other than using several rather lazy nested ifs. I tried looking for a way to query where a field is any, but didn't succeed. How can I search for the documents I need in the cases I can't be sure about how many and which fields are going to be used.

1 answer

  • answered 2020-06-27 23:09 Capeudinho

    I found a way by using the following code in the controller. The model is not the log one, but the idea is the same. It basically checks if a name has been given. If so, it looks for every document with a name that contains what was given. If not, if looks for every document that has the name field (which, in this case of mine, all users have).

    if (name === "")
        var namevalue = {$exists: true};
        var namevalue = {"$regex": name, "$options": "i"};
    const users = await User.paginate ({name: namevalue, owner}, {page, limit: 10});