我是 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。
关于javascript - 使用 Node JS 和 MongoDB 过滤查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61032067/