我對使用Node.js比較新。我已經成功創建了一個應用程序,用於獲取用戶數據(特別是創建用戶的日期)並分析每日,每週,每月和每年的用戶數量。這是通過郵差成功測試的。節點應用程序連接到pugjs
我已經成功安裝pugjs,並試圖將計算的數據傳輸到帕格文件。我有一個控制器,模型和路由文件下的所有表示:
userAPIController.js
'use strict';
const mongoose = require('mongoose'),
express = require('express'),
app = express(),
moment = require('moment'),
pug = require('pug'),
User = mongoose.model('Users'),
compiledFunction = pug.compile('results.pug');
exports.list_all_users = function(req, res) {
User.find({}, function(err, user) {
if (err)
res.send(err);
res.json(user);
});
};
exports.create_a_user = function(req, res) {
var new_task = new User(req.body);
new_task.save(function(err, user) {
if (err)
res.send(err);
res.json(user);
});
};
exports.calculate = function(req, res) {
User.find({}, function(err, userArray) { //the second parameter, userArray, is an array that is returned to you.
if (err)
res.send(err);
var daily_count = 0;
var weekly_count = 0;
var monthly_count = 0;
var yearly_count = 0;
var total_count = 0;
for (var i = 0; i < userArray.length; i++) {
total_count++;
var timeString = userArray[i].Created_date;
var dayString = timeString.getUTCDate();
var monthString = timeString.getUTCMonth()+1;
var yearString = timeString.getUTCFullYear();
var todaysDate = new Date();
var todaysDay = todaysDate.getUTCDate();
var todaysMonth = todaysDate.getUTCMonth()+1;
var todaysYear = todaysDate.getUTCFullYear();
// Calculating Daily Users
if (dayString === todaysDay && monthString === todaysMonth && yearString === todaysYear) {
daily_count += 1;
}
// Calculating Weekly Users
var weekDifference = todaysDay - dayString;
if (monthString === todaysMonth && yearString === todaysYear && (weekDifference >= 0 && weekDifference <= 7)) {
weekly_count += 1;
}
// Calculating Monthly Users
if (monthString === todaysMonth && yearString === todaysYear) {
monthly_count += 1;
}
// Calculating Yearly Users
if (yearString === todaysYear) {
yearly_count += 1;
}
}
res.json({
"daily_count":daily_count,
"weekly_count":weekly_count,
"monthly_count":monthly_count,
"yearly_count":yearly_count,
"total_count":total_count
});
});
};
exports.delete_a_user = function(req, res) {
User.remove({
_id: req.params.userId
}, function(err, user) {
if (err)
res.send(err);
res.json({ message: 'User successfully deleted' });
});
};
隨着userAPIModel.js,userAPIRoutes.js和server.js文件以及所有建模本教程後: https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd
我也有一個與帕格文件裏面的意見文件夾,我不確定如何把我的每日,每週,每月和每年的用戶(如在控制器中所見)並將它們轉移到帕格。我瞭解#{}帕格語法;但是我不確定如何獲取信息。我試着要去到數據所在的控制器文件,並使用res.send功能,如:
app.get('/', function (req, res) {
res.send(compiledFunction({
dCount: daily_count,
wCount: weekly_count,
mCount: monthly_count,
yCount: yearly_count,
tCount: total_count
}));
})
,然後導入它從那裏帕格。唯一值得關注的是,我不相信這是將控制器鏈接到帕格文件的正確方法,或者我正在使用正確的功能。
我究竟做錯了什麼?我想我會把上述內容放在控制器中,因爲這是輸出JSON的地方,但我習慣把它放在服務器文件中。