0

I am new to MangoDB and Node JS. I have always worked on SQL databases and I do not know the syntax of MongoDB well. I wanna try to filter the array that I receive from a MongoDB database. I know that JavaScript has a .filter() function to filter just the results that contain a string. Is it best practice to get all the objects from MongoDB and filter in Node or do I let MongoDB do the filtering?

My Node.JS project is a back-end project using Node.JS and Express to do CRUD operations on a MongoDB database. In the request I send a parameter called 'equalTo' that contains the value that should be filtered on.

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);
   });
});

The filtering should be an OR filter where all results where either the name or the cropName should CONTAIN the value of the string. If it is possible I would also like the comparison to ignore uppercase's. Here is a schema for the Plot object:

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"
});

1 Answer 1

2

The format is the following:

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

For further information you can read here https://docs.mongodb.com/manual/reference/operator/query/or/ You may replace the strings above in your case with equalTo.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. The only question I still have is how do i combine this with a contains and ignoring uppercase?
@user3566338 You can try some regular expression over the string.
{ name: { $regex: ".*" + query + ".*", $options: "i" } }. This did the trick.
BTW, if you are building in React you may consider doing filtering over there, just an idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.