'Searching mongoDB not by primary id
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?
Solution 1:[1]
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});
Solution 2:[2]
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohammad |
| Solution 2 |
