8

Say you have a very long generic function you want to use over multiple schemas, and each schema has a different name for the field you're querying (and possibly different type of value -- string, number, etc.)

function foo (field, value){
    Model.find({field: value});
}

foo('idfoo', 'xx');
foo('idbar', 5);

I tried to do something like this as a proof of concept in mongoose and it seems it will only work if you use a variable for value, but you can't for field.

Is this impossible?

Mat
  • 202,337
  • 40
  • 393
  • 406
PGT
  • 1,468
  • 20
  • 34

4 Answers4

16

Just put the variable in []

function foo (field, value){
    Model.find({[field]: value});
}

foo('idfoo', 'xx');
foo('idbar', 5);
KiwenLau
  • 2,502
  • 1
  • 19
  • 23
10

You could use the built in where function, making the call to the function you've shown unnecessary:

Model.find().where(fieldName, value).exec(function(err, results) { });

And you could do more than one via chaining:

Model.find().where(field1, val1).where(field2, val2).exec(...)

It also can be rich, supporting nested properties and other operators:

Model.find().where('orders.total').gt(1500).exec(...)
WiredPrairie
  • 58,954
  • 17
  • 116
  • 143
7
function foo(field, value) {
  var query = {};
  query[field] = value;
  Model.find(query)...
}
robertklep
  • 198,204
  • 35
  • 394
  • 381
0

If you want to search by generic field, try the below code

import { Request, Response } from "express";
import Client from "../models/client";

const search = async (req: Request, res: Response) => {

 try {
  const keyword = req.query.keyword || "";
  const field: any = req.query.field || "email"; // default field

  let clients = await Client.find(
   { [field]: { $regex: ".*(?i)" + keyword + ".*" } },
  );

  if (clients?.length) {
   res.status(200).send(clients);
  } else {
   res.status(200).send("no match");
  }
 } catch (error) {
  res.status(500).send(error.message);
 }
};

export default {
 search,
};
Jobelle
  • 2,717
  • 1
  • 15
  • 26
bensbenj
  • 391
  • 3
  • 7