Agenda Cannot read property insertOne of undefined

1.4k views Asked by At

I am trying to create and schedule jobs with agenda. So i split it into two files, one file the consumer creates jobs and the other file the producer schedules jobs.

this is the consumer file

const Agenda = require("agenda");
async function run() {
    try {
        const agenda = new Agenda({
            db: {
                address: process.env.MONGODB_URL,
                collection: 'agendaJobs',
                options: {
                    useUnifiedTopology: true
                }
            }
        });

        agenda.define('ticket creation', async (job, done) => {
            const { time } = job.attrs.data;
            console.log(time);
            done();
        });

        agenda.on("ready", function () {
            agenda.start();
            console.log('Agenda Started');
        });
        //await agenda.start();

    } catch (error) {
        console.error(error);
        process.exit(-1);
    }

}

module.exports = {
    run: run
};

and the producers file is

//import { default as Agenda } from 'agenda';
const Agenda = require("agenda");

const jobs = async (job) => {
    try {
        const agenda = new Agenda({
            db: {
                address: process.env.MONGODB_URL,
                collection: 'agendaJobs',
                options: {
                    useUnifiedTopology: true
                }
            }
        });

        const created = await agenda.schedule(job.time, 'ticket creation', {
            time: job.time
        });
        
        return created;
        
    } catch (error) {
        console.error(error);
        process.exit(-1);
    }
};

module.exports = jobs;

and this is my controller where i use it

const jobs = require('./producer');
const { run } = require('./consumer');
run();

app.post('/create/job', async (req, res) => {
    try {
        const { time } = req.body;
        await jobs({
            time: time
        });
        return res.status(200).send({
            success: true,
            message: 'Job created'
        });
    } catch (error) {
        return res.status(error.status).send(error);
    }
});

is there anywhere i am wrong, i know this connects to the db

an example of the body sent to the controller

{
    "time": "3 minutes"
}

i have used the node debugger to trace the error, it always fails at a line that looks like this, but i don't know what is causing it

yield schedule(this).save()

then shows an error in the terminal saying

TypeError: Cannot read property 'insertOne' of undefined

** The props property of this is always undefined

1

There are 1 answers

0
Trejon House On

https://github.com/agenda/agenda/issues/335#issuecomment-249154993

        agenda.on("ready", async () => {
             const created = await agenda.schedule(job.time, 'ticket creation', {
                time: job.time
             });
        });