Bennyh961
Bennyh961

Reputation: 179

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

Upvotes: 0

Views: 91

Answers (1)

Dipten
Dipten

Reputation: 1066

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

Upvotes: 1

Related Questions