I'm creating an Agenda function (similar to a cron job) to email us a list of new users every night. I think maybe I don't understand how the data is returned from the Mongoose call as I seem to be getting duplicate emails by the same number of results are returned from the Mongoose query. (Postmark is an email api here)
Here's a trimmed down version of my code:
var Agenda = require('agenda');
var agenda = new Agenda({db: { address: 'mongodb://localhost/example }});
var User = mongoose.model('User', userSchema);
agenda.define('example email', function() {
User.find({ date: { $gt: date }}, function (err, users) {
if (err) // handle error
postmark.send({
// setup and send email with users listed in body
}, function(error, success) {
if (error) // handle error
console.log('Sent successfully');
});
});
// Run every day at 2am
agenda.every('* 2 * * *', 'example email');
agenda.start();
So firstly the email sends straight away as I run the server (this code is in app.js) - I'm not sure why that is. But the main issue is that I receive multiple emails - they were received exactly 10 minutes apart, whether that is of any relevance. So for example the DB query returned 4 users so I received 4 emails of exactly the same data.
Do I need to close the query or something? I'm not looping through labels before sending the email - I thought that model.find() would just return one array of labels? But seems to be returning the same data each time for every label in labels. Going mad here.
I've just tried it on my local machine and there isn't the same problem, but it's the exact same code. I've also checked the Agenda DB to make sure there isn't duplicate jobs.