Search code examples
arraysmongodbmongoosemongodb-querymongoose-schema

How to use Mongoose queries to filter to the documents that have a specified value inside an array-typed field?


I know how to use Model.findOne but I wish to use Mongoose queries for the same task.

How is it possible to do this using Mongoose queries?

So I have this old code:

Notification.find(
  {
    subscribers: user.id
  }
)
...

and I am working on this alternative code:

const r = await Notification.find()
  .where("subscribers")
  .equals(user.id)
...

But I don't think .equals works for this case since subscribers is an array of ObjectIds and user.id is an ObjectId-based string.

I have searched through the official API docs and did not found an answer. There are no error messages.


Solution

  • I found the Query.prototype.all method. Now the code looks like this:

    const r = await Notification.find().where("subscribers").all([user.id]);
    ...