如何在Node JS应用程序

时间:2017-02-03 07:10:08

标签: javascript node.js mongodb cron

我已经开始学习Node JS几天了。

我的Node JS应用程序有一个get api,当http:// localhost:portnumber / mybooks url被触发时,它以json格式从MongoDB数据库中获取书籍信息。

书籍架构有四个字段,即标题,作者,类别和价格。 现在,我想介绍一个每小时每10分钟和第50分钟运行一次的cron作业。它将检查是否有任何价格超过100的书(此处货币无关紧要),它将从数据库中删除该记录(或文档)。意味着它将在上午7:10,上午7:50运行,然后在下一个小时在上午8:10和上午8:50运行,依此类推。

我从应用程序文件夹中使用命令./bin/www启动我的应用程序。但是,我无法弄清楚如何实现这个cron作业服务以及放置此代码的位置(在哪个文件中),以便在我启动应用程序时使其在上述指定时间运行。

我在这里包含了我迄今为止开发的应用程序的一些代码,让你看看。目前它对于休息api工作正常。

这是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;

这是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;

和mybook.model:

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);

有人可以帮我了解如何以及在哪个文件中实现node-schedule cron以满足我的要求?

1 个答案:

答案 0 :(得分:3)

我可以弄明白该怎么做。我从https://www.npmjs.com/package/node-schedule得到了这个想法。

虽然它不是一个确切的解决方案,但接近。在这种情况下,cron作业每时每刻都在运行,但是没有实现删除。可以将cron调度程序代码放在index.js中,如下所示:

var s =  require('node-schedule');    
var j = schedule.scheduleJob('* * * * *', function() {

Book1.find({price : {$gt:100}} , function(err, result) {    
   if(err) {
    console.log(err);
  }
  else {
    if(!result) {
      console.log("No book found");
    } else {          
      console.log("Found a book with title "+result.title);
    }         
  }    
});

如果有人能够完成这一点,那么确切的要求会有所帮助。谢谢。

相关问题