使用NodeJS和jQuery查询MongDB数据库

时间:2015-06-29 10:53:24

标签: javascript jquery node.js mongodb

我试图查询使用MongoDB构建的数据库(使用Mongoose作为ODM)并在页面上显示结果。数据库将数据(包括日期:'日期'和链接:' www.example.com')存储在我命名为'条目'的集合中。我有两个用于访问数据库的视图:一个视图,它将利用日期键在特定日期显示正确的链接;以及我可以查看,添加和删除条目的数据库视图。我能以某种方式遍历数据库视图的条目并将它们添加到DOM中,但是当我为小部件视图尝试相同时,我似乎无法从条目集合中访问JSON对象。我使用Jade作为HTML的预处理器

我的app.js文件是这样的:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var router = express.Router();
//database stuff
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

//connect to the data store and the set up the database
var db = mongoose.connection;

//connect to the database
var conn = mongoose.connect('mongodb://localhost/Mandela_Diaries/data');

//Create a model which connects to the schema and entries collection in the Mandela_Diaries database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");

mongoose.connection.on("open", function() {
  console.log("mongodb is connected!");
});

var routes = require('./models/index');
var users = require('./routes/users');
var database = require('./routes/database');
var methodOverride = require('method-override');
var templatemain = require('./routes/template-main');

var app = express();

// Methodoverride at the top
app.use(methodOverride('_method'));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

//serving static files
app.use('/public', express.static(__dirname + '/public'));
app.use('/public', express.static(__dirname + '/css'));
app.use('/public', express.static(__dirname + '/js'));
app.use('/public', express.static(__dirname + '/images'));
app.use('/public', express.static(__dirname + '/node_modules'));

app.use('/', routes);

app.use('/', routes);

app.use('/', routes);
app.use('/database', database);
app.use('/create', database);
app.use('/delete', database);
app.use('/:id', database);
// app.use('/database/#{entry._id}?/delete', database);

// 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 handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;
module.exports.Entry = Entry;

app.listen(8080);

console.log("The server has started");

我的database.js路由器代码是这样的:

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Entry = mongoose.model('Entry');

//The route for getting data for the database - GET form
router.get("/", function(req, res) {
  //Send the current entries to the page
  Entry.find({}, function(err, entries) {
    console.log(entries);
    if(err) {
      res.status(404).json({"error": "not found", "err":err});
      return;
    } else {
      res.render('database', {title: 'database', entries: entries});
      //console.log(entries);
      //entries.forEach(printjson);
    }
  });

});

//The route for posting data to the database - POST
router.post('/', function(req, res) {
  var newEntry = new Entry(req.body);
  newEntry.save(function(err, entries){
    if (err !== null) {
      res.status(500).json(err);
    } else {
      res.redirect('database');
    };
  });
});

//The route for deleting data to the database - Delete/remove todo item by its id
// Changed path from `/` to `/:id`
    router.delete('/:id', function (req, res) {
        Entry.findById(req.params.id)
            .exec(function(err, entries) {
               // changed `if (err || !doc)` to `if (err || !entries)`
                if (err || !entries) {
                    res.statusCode = 404;
                    res.send({});
                } else {
                    entries.remove(function(err) {
                        if (err) {
                            res.statusCode = 403;
                            res.send(err);
                        } else {
                            res.send('Deleted entry with link: ', entries.link);
                        }
                    });
                }
            });
    });

module.exports = router;

我的index.js路由器代码是这样的:

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Entry = mongoose.model('Entry');
var moment = require('moment');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('/', { title: 'Express' });
  Entry.find({}, function(err, entries) {
        if(err) {
            res.status(404).json({"error": "not found", "err":err});
            return;
        } else {
            res.render('/', {title: 'database',  entries: entries});
        }
    });
});

console.log("new code works");

module.exports = router;

运行jQuery的script.js代码根据日期附加正确的视频链接是这样的:

$(document).ready(function() {
//Date picker jQuery
$(function() {
    $( ".datepicker" ).datepicker();
    $( "#format" ).change(function() {
      $( ".datepicker" ).datepicker( "option", "dateFormat", $( this ).val() );
    });
  });

var browserDate = new Date();
var videoDate = new Date(1962);
//var month = browserDate.getMonth() + 1;
//var day = browserDate.getDate();
//var year = browserDate.getFullYear();

var context = browserDate - videoDate;

$('#context').innerHTML = "ON THIS DAY " + context + " YEARS AGO:";
console.log("ON THIS DAY " + context + " YEARS AGO:");

console.log("This worked!!");
console.log(browserDate);

});

我对index.jade的Jade代码是这样的:

extends layout

block content
   #widget.container
      .row
        #header.col-xs-12.header
          img#Mandela_Logo(src='/public/images/Logo_MandelaDiaries.png')
      .row
        #context.col-xs-12
      .row
        #videos.col-xs-12
          .embed-responsive.embed-responsive-4by3
            iframe(width='300', height='169', src='https://www.youtube.com/embed/4HqtAMHrJ8s', frameborder='0', allowfullscreen='')
      .row
        #footer.col-xs-12
          img#NMF_logo(src='/public/images/Logo_NMF.png')
          img#SABC_logo(src='/public/images/Logo_SABCNews.png')

我似乎无法让我的jQuery在这里工作。我只想获取JSON对象并循环遍历它并根据浏览器日期查找相关日期,并将相应的链接附加到我的小部件中的iframe。

1 个答案:

答案 0 :(得分:1)

为简化起见,您可以使用 momentjs 库来处理日期。在您的使用案例中,您希望使用 fromNow() 方法,该方法显示从现在起的相对时间,例如

moment([2011, 0, 29]).fromNow(); // 4 years ago
moment("1962-04-08T09:48:16.189Z").fromNow() // 53 years ago 

要在视图中使用momentjs库,您需要将其添加到您的快速应用程序本地,如下所示:

express = require('express');
...
var app = express();
app.locals.moment = require('moment');

由于您可以在Jade视图中使用纯JavaScript代码,因此您可以轻松地执行以下操作:

extends layout

block content
   #widget.container
      .row
        #header.col-xs-12.header
          img#Mandela_Logo(src='/public/images/Logo_MandelaDiaries.png')
      .row
        #context.col-xs-12
            each entry in entries
                p= 'ON THIS DAY ' + moment(entry.date).fromNow() + ' -  Link: ' + entry.link + ' '              
      .row
        #videos.col-xs-12
          .embed-responsive.embed-responsive-4by3
            iframe(width='300', height='169', src='https://www.youtube.com/embed/4HqtAMHrJ8s', frameborder='0', allowfullscreen='')
      .row
        #footer.col-xs-12
          img#NMF_logo(src='/public/images/Logo_NMF.png')
          img#SABC_logo(src='/public/images/Logo_SABCNews.png')

<强> Demo

来源Making use of utility libraries in server-side Jade templates