【问题标题】:Filtering a query using Node JS and MongoDB使用 Node JS 和 MongoDB 过滤查询
【发布时间】:2020-04-04 17:31:51
【问题描述】:

我是 MangoDB 和 Node JS 的新手。我一直在研究 SQL 数据库,我不太了解 MongoDB 的语法。我想尝试过滤从 MongoDB 数据库收到的数组。我知道 JavaScript 有一个 .filter() 函数来过滤包含字符串的结果。最佳实践是从 MongoDB 获取所有对象并在 Node 中过滤,还是让 MongoDB 进行过滤?

我的 Node.JS 项目是一个使用 Node.JS 和 Express 对 MongoDB 数据库进行 CRUD 操作的后端项目。在请求中,我发送了一个名为“equalTo”的参数,其中包含应该过滤的值。

var router = express.Router();
var Plot = require("./models/plot");

...

router.get("/plots", (req, res) => {
   let query = "" + req.query.equalTo;
   Plot.find((err, plots) => {
      if (err) {
         res.send(err);
      }
      res.json(plots);
   });
});

过滤应该是一个 OR 过滤器,其中namecropName 应包含字符串值的所有结果。如果可能的话,我还希望比较忽略大写字母。这是Plot 对象的架构:

const plotSchema = mongoose.Schema({
   area: {
      type: String,
      required: true
   },
   comments: {
      type: String,
      required: true
   },
   cropGroupName: {
      type: String,
      required: true
   },
   cropName: {
      type: String,
      required: true
   },
   name: {
      type: String,
      required: true
   },
   plotId: {
      type: Number,
      required: true
   },
   coords: {
      type: [],
      required: true
   },
}, {
   collection: "plots"
});

【问题讨论】:

    标签: javascript node.js mongodb filter


    【解决方案1】:

    格式如下:

    Plot.find({$or:[{name: "anyname"},{cropName:"othername"}]})
    

    有关更多信息,您可以阅读此处https://docs.mongodb.com/manual/reference/operator/query/or/ 您可以用 equalTo 替换上面的字符串。

    【讨论】:

    • 谢谢。我唯一的问题是如何将它与包含并忽略大写结合起来?
    • @user3566338 你可以在字符串上尝试一些正则表达式。
    • { name: { $regex: ".*" + query + ".*", $options: "i" } }。这成功了。
    • 顺便说一句,如果你在 React 中构建,你可以考虑在那里进行过滤,只是一个想法。
    猜你喜欢
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    相关资源
    最近更新 更多