javascript - 使用 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/or/ 您可以用 equalTo 替换上面的字符串。
推荐阅读
- python - Elasticsearch、映射、日期映射问题
- c# - 使用 c# 进程对象获取有关 citrix 进程的唯一信息
- javascript - 如何在 javascript 中定位这些元素?(更多下文)
- python - 实现广度优先搜索
- java - 通过配置文件禁用 spring-context-indexer
- r - 如何根据复选框输入创建反应表?
- python - python 如何重新对齐我的图表,如图所示
- python-3.x - 限制python中的最大线程数,但在一个完成后继续加入
- python - 如果输入列表的值为数字,则将索引添加到新列表
- ruby-on-rails - 在 rails 中链接作用域以获得其中一个或两个作用域的结果