【发布时间】: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 过滤器,其中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"
});
【问题讨论】:
标签: javascript node.js mongodb filter