首页 > 解决方案 > 使用 Node JS 和 MongoDB 过滤查询

问题描述

我是 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 过滤器,其中所有结果都name应该cropName包含字符串的值。如果可能的话,我还希望比较忽略大写字母。这是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"
});

标签: javascriptnode.jsmongodbfilter

解决方案


格式如下:

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

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


推荐阅读