如何在快递js中构建站点地图?

时间:2014-11-27 03:29:37

标签: javascript mongodb express sitemap

我尝试使用位于https://www.npmjs.org/package/sitemap

的sitemap.js包

我可以在站点地图中推送网址。但我想根据我从mongodb检索的数据添加网址。我知道如何创建网址来提供站点地图,但是因为从mongo中查找数据是一个回调,在我获取数据之前,会调用/sitemap.xml的路由器,因此我无法向站点地图提供更多网址。

以下是我的路线文件的快照

var colors = require('colors'); 
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var sm = require('sitemap');
var _ = require('underscore');

//these models are found in the /models folder
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');


var trendSchema = mongoose.Schema({
    tName: String,
    tName_h: String,    
    region: String
  });

var Trend = mongoose.model('Trend', trendSchema);

// var Trend = mongoose.model('Trend'); 






console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');




var tfind = function  (trends) {
    Trend.find(function (err, trends) {
        if (err) {
            console.log(err);
            return next(err);
        }

    console.log('trends =', trends);
        var plucked = _.pluck(trends, 'tName');

        // console.log('plucked  trends',plucked);

        // console.log(' sitemap urls   = ', sitemap.urls);
        // sitemap.urls.length = 0;
        // sitemap.urls.push({ url: '/page-10/', changefreq: 'daily', priority: 0.3 });

    });
}


tfind.done(function (text) {
        console.log(' text   = ', text );
});




var sitemap = sm.createSitemap ({
      hostname: 'http://example.com',
      cacheTime: 600000,        // 600 sec - cache purge period
      urls: [
        { url: '/page-1/',  changefreq: 'daily', priority: 0.3 },
        { url: '/page-2/',  changefreq: 'monthly',  priority: 0.7 },
        { url: '/page-3/' }     // changefreq: 'weekly',  priority: 0.5
      ]
    });

router.get('/sitemap.xml', function(req, res) {
  sitemap.toXML( function (xml) {
      res.header('Content-Type', 'application/xml');
      res.send( xml );
  });
});



sitemap.urls.push({ url: '/page-5/', changefreq: 'daily', priority: 0.3 });
sitemap.urls.push({ url: '/page-7/', changefreq: 'daily', priority: 0.3 });
// sitemap.urls.push({ url: '/page-9/', changefreq: 'daily', priority: 0.3 });

console.log(' app.js  sitemap.urls == ', sitemap.urls);

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,您希望在呈现XML文件以进行响应之前,将从MongoDB获取的数据添加到您的站点地图中。

首先,Node.js是异步的,MongoDB驱动程序也是基于此。因此,您的路由句柄应该在其中执行搜索,并且当mongo返回文档时,只有在您确定所有内容都完成后,才会发回响应。

注意:为简洁起见,我不是在这里编写配置和错误处理程序。另外,请始终将您的expressjs配置放在模块导入的正下方。

var mongoose = require('mongoose');
.
.
var app = express();

// YOUR CONFIG SHOULD ALWAYS BE ON TOP

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

// YOUR CODE WAS MISSING A MONGODB CONNECTION SETUP
mongoose.connect('mongodb://localhost:27017/news', function () {
  console.log('Database Connected');
});

var sitemap = sm.createSitemap ({
  hostname: 'http://example.com',
  cacheTime: 600000,        // 600 sec - cache purge period
  urls: [
    { url: '/page-1/',  changefreq: 'daily', priority: 0.3 },
    { url: '/page-2/',  changefreq: 'monthly',  priority: 0.7 },
    { url: '/page-3/' }     // changefreq: 'weekly',  priority: 0.5
  ]
});

var trendSchema = mongoose.Schema({
  tName: String,
  tName_h: String,    
  region: String
});

var Trend = mongoose.model('Trend', trendSchema);

app.get('/sitemap.xml', function(req, res) {
  Trend.find(function (err, trends) {
    if (err) {
      console.log(err);
      return next(err);
    }
    trends.forEach(function(trend, index) {

      // Place your data extraction/insertion logic here
      sitemap.urls.push({ url: trend.tName, changefreq: 'daily', priority: 0.3 });

      if(index == trends.length-1) {
        sitemap.toXML( function (xml) {
          res.header('Content-Type', 'application/xml');
          res.send( xml );
        });
      }
    });
  });
});

var server = app.listen(3000, function() {
  console.log('Express server listening on port ' + server.address().port);
});