Filter documents based on filter function

254 views
Skip to first unread message

Muhammad Tayyab Sheikh

unread,
Jul 10, 2019, 3:13:55 AM7/10/19
to Mongoose Node.JS ODM
Hi!
In mongoose we can search Schema using particular values of a  field such as:
schema.findOne({field: 'abcd'}); 
But I want to pass a custom filter function so  if that filter function returns true only the that sub document is selected otherwise not. For example:

schema.findOne(function (document) {
if(condition on document) {
   
return true; //Yes select this element
}
else {
   
return false; // No don't select this document
}
});


Richard Bateman

unread,
Aug 21, 2019, 11:12:26 PM8/21/19
to mongoo...@googlegroups.com
You can do that using $where, but it's not very efficient and can't use indexes.


e.g.


schema
.findOne({$where: "return (condition on this);"});



You'd be better off using $expr though as it's more efficient and can probably do what you need.

Richard



--
Documentation - http://mongoosejs.com/
Plugins - http://plugins.mongoosejs.com/
Bug Reports - http://github.com/learnboost/mongoose
Production Examples - http://mongoosejs.tumblr.com/
StackOverflow - http://stackoverflow.com/questions/tagged/mongoose
Google Groups - https://groups.google.com/forum/?fromgroups#!forum/mongoose-orm
Twitter - https://twitter.com/mongoosejs
IRC - #mongoosejs
---
You received this message because you are subscribed to the Google Groups "Mongoose Node.JS ODM" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoose-orm...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongoose-orm/e3f0db25-474f-4a1e-af33-9c0a0c34982e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages