Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mongoose findOne not working with array search query

i have a document that store array of strings , i want search by id and by array contain. i used 2 method , both of them return null

the Schema example:

const exampleSchema = new mongoose.Schema{
id : objectId(),
list :Array // will store other id's
}
const Example= mongoose.model("Example", exampleSchema );

// this work
const friend = await Example.findOne({ _id: req.body.friendId }); // return the docuemnt

//this not work - return null
const friend = await Example.findOne({ _id: req.body.friendId, pending: { $in: [req.body.userId] } });



also i tried $elemMatch that not work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As per the schema you mentioned it has 2 fields, _id and list.
So your query need to modify as below.

const friend = await Example.findOne({ _id: req.body.friendId, list: { $in: [req.body.userId] } });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading