Get documents if one property don't have matches

Viewed 151

I have a schema on Mongoose something like this:

  const customerSchema = new mongoose.Schema({ name: String, age: Number, email: String });
  const Customer = mongoose.model('Customer', customerSchema);

And two models like this:

  Customer.create({ name: 'A', age: 30, email: 'a@foo.bar' });
  Customer.create({ name: 'B', age: 28, email: 'b@foo.bar' });

I want to make a find() of Customers

So if I try something like this:

Customer.find({ age: { $gte: 30 } });

I'm getting one document (A). But whats happend if I send a property who has no match, like this:

Customer.find({ age: { $gte: 30 }, name: 'C' });

Name has no matchs so that makes me don't have any document, but I want at least to get the document A because age matches.

How can I make a find() and get all the documents who match any property?

UPD:

What if I make the query like this:

let query = {};
let { name, email } = req.query;
if ( name ) { query.name = new RegExp(name, "i") };
if ( email ) { query.email = new RegExp(email, "i") };
Customer.find(query);
1 Answers

You can use the $or operator


db.customers.insert([
  {age: 40},
  {age: 20},
  {age: 20,  name:'C'}
])


db.customers.find({
  $or: [
    { age: { $gte: 30 } }, 
    { name: 'C' }
  ]
})

//{ "_id" : ObjectId("6030bdf06cbb3d6b4bf01f40"), "age" : 40 }
//{ "_id" : ObjectId("6030bdf96cbb3d6b4bf01f42"), "age" : 20, "name" : "C" }
Related