skip to Main Content

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?

2

Answers


  1. 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();
    
    Login or Signup to reply.
  2. 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}); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search