有没有一种方法可以在mongoose中的find()中使用变量作为字段名

Is there a way to use a variable for the field name in a find() in mongoose?

本文关键字:变量 字段 find mongoose 一种 方法 有没有 中的      更新时间:2024-01-28

假设您有一个非常长的通用函数要在多个模式上使用,并且每个模式都有一个不同的名称用于查询的字段(可能还有不同类型的值——字符串、数字等)

function foo (field, value){
    Model.find({field: value});
}
foo('idfoo', 'xx');
foo('idbar', 5);

我试着在猫鼬中做这样的事情来证明概念,似乎只有当你使用变量作为值时,它才会起作用,但你不能使用字段。

这不可能吗?

只需将变量放入[]

function foo (field, value){
    Model.find({[field]: value});
}
foo('idfoo', 'xx');
foo('idbar', 5);

您可以使用内置的where函数,使对显示的函数的调用变得不必要:

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

你可以通过链接做不止一件事:

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

它也可以是丰富的,支持嵌套属性和其他运算符:

Model.find().where('orders.total').gt(1500).exec(...)
function foo(field, value) {
  var query = {};
  query[field] = value;
  Model.find(query)...
}

如果您想按通用字段搜索,请尝试以下代码

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,
};