It has been a few days I have started learning Node JS.
My Node JS application has a get api which fetches the books information from the MongoDB database in json format when the http://localhost:portnumber/mybooks url is fired.
The book schema has four fields namely title, author, category and price. Now, I want to introduce a cron job which will run every 10th and 50th minute of every hour. It will check if there is any book with price more than 100 (currency does not matter here), it will delete that record (or document) from the database. Means it will run at 7:10AM, 7:50AM , then in the next hour at 8:10AM and 8:50AM and so on.
I am starting my application with command ./bin/www from the application folder. However, I am not able to figure out how to implement this cron job service and where (in which file) to put this code so as to make it run at the above specified time whenever I start my application.
I am including the bits of code of my so-far developed application here to let you have a look. Currently it is working fine for the get rest api.
This is app.js:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
This is index.js :
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Book1 = require('../models/mybook.model');
var db = 'mongodb://localhost/mybookdb';
var mongoose = require('mongoose');
mongoose.connect(db);
var conn = mongoose.connection;
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/mybooks', function(req, res) {
console.log('Showing all books');
Book1.find({})
.exec(function(err,records){
if(err){
res.send('error has occured');
}else{
console.log(records);
res.json(records);
}
});
});
module.exports = router;
and mybook.model as :
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BookSchema = new Schema({
title:String,
author:String,
category:String,
price: Number
});
module.exports = mongoose.model('Book', BookSchema);
Can anybody help me with how and in which file to implement the node-schedule cron to serve my requirement ?