使用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"
});
网络弥赛亚

格式如下:

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

有关更多信息,您可以在这里阅读https://docs.mongodb.com/manual/reference/operator/query/或/您可以将上面的字符串替换为equalTo。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章