Home > other >  Searching mongoDB not by primary id
Searching mongoDB not by primary id

Time:04-12

I have a notification collection and inside I have documents like this :

id: 6253ec60facb2ee68475510e;
companyId: 6253asdsad0facb2ee68475510e;
workStatus: true


id: 6253ec60abcb2ee68475510e;
companyId: 6253ec60afva2ee68475510e;
workStatus: true

I want to search documents by the companyId and not id. When I do this :

 const notification = await Notification.findById(req.params.companyId); 

It's searching by id(primary ID).

I'm new to programming. Can someone help me with this?

CodePudding user response:

you are using findById and it finds a document by its ID you should use findOne()

 const notification = await Notification.findOne({companyId: req.params.companyId}); 

CodePudding user response:

The findById() function is used to find a single document by its _id field. You can use find() or findOne() and pass the companyId field.

Difference between find() and findOne() is the findOne() returns first document if query matches, otherwise returns null. The find() method does not return null, it returns a cursor.

For example write something like this:

await Notification.find({ companyId: req.params.companyId }).exec();
  • Related