Is it possible to use MongoDB aggregation commands in local queries? Like distinct() or count()?
Hey @salomo — with the Payload Local API, this is currently not possible. But, you can do this via one of two ways:
payload.collections[collectionSlug].Model
. Then, you can do whatever you can do with Mongoose.Does this help you out?
Hi @jmikrut,
thank you for the fast response.
With raw MongoDB by writing Mongo queries directly against your database
Is it possible to open a second connection to the database within payload? Doesn’t that interfere with the connection that payload already has opened?
Hi @salomo,
Is it possible to open a second connection to the database within payload? Doesn’t that interfere with the connection that payload already has opened?
That shouldn't be an issue, you should be able to have many connections open concurrently unless you've limited that on your database.
If you do have trouble, you can customize the mongoose connection with the mongoOptions
setting used for Payload. https://payloadcms.com/docs/getting-started/installation#server
Mongoose documents those options here: https://mongoosejs.com/docs/connections.html
Let us konw if you have trouble!
Hi @DanRibbens,
With Mongoose. You can access the Mongoose model that corresponds to your Payload collection via payload.collections[collectionSlug].Model. Then, you can do whatever you can do with Mongoose.
I tried the Mongoose solution and it works.
Thanks for your help!
Hey @salomo — with the Payload Local API, this is currently not possible. But, you can do this via one of two ways:
* With Mongoose. You can access the Mongoose model that corresponds to your Payload collection via `payload.collections[collectionSlug].Model`. Then, you can do whatever you can do with Mongoose. * With raw MongoDB by writing Mongo queries directly against your database
Does this help you out?
Hey @jmikrut, Could you please tell me how to do I access payload collection in my custom controller? I'm having some trouble while accessing the collection, maybe I'm not accessing it in the right way. It would be great if you could point out some piece of code.
You can do it like this:
const payload = require('payload');
payload.collections['collection_name'].Model.distinct('field_name', {status: {$eq: '*condition*'}}, async (err, data) => {
if (err) {
// handle error
} else {
// work with data
}
});
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.