如何在MongoDB中存储和区分数据?

时间:2019-01-31 08:21:55

标签: javascript node.js mongodb express mongoose

请注意,我是新编码员。

我不知道如何在Mongo中高效地讲述数据,因此我可以重用它并随时间进行比较。

我正在构建一个管理仪表板,在该仪表板上我从HTML收集数据并将其存储在Mongo Collections和定义的模式中。数据将转换为图形供用户查看。

现在,我正在收集今年的数据。 明年,我将收集完全相同或几乎完全相同的数据。

然后我要创建比较。

最初,我想到创建多个模型来进行区分。

所以从下面的代码中可以找到

今年的模型将是2019manageSchema .... 明年的模型将是2020manageSchema ... 但这些架构与我收集相同数据的方式完全相同。

但是我认为这不是最佳实践。

此外,我在考虑路线,要求所有mdoel并使其通过每条路线会很混乱。

模式

var mongoose = require("mongoose"),
    math     = require('mathjs');

*****DATABASE CONFIG*******
var manageSchema = new mongoose.Schema({
   period: String,
   managers: Number,
   staffs: Number,
   staffcosts: Number,
   headcountavg: Number,
   frontliners: Number,
   supportfunc: Number,
   depthratio: Number,
   totalrevenue: Number,
   grossprofit: Number,
   noofworkdays: Number,
   sickleavestaken: Number,
   unauthleavestaken: Number,
   authleavestaken: Number,
   eesmanagerscoreprev: Number,
   eesmanagerscore: Number,
   eesrecognitionscoreprev: Number,    
   eesrecognitionscore: Number,
    created: {type: Date, default: Date.now},
    user: {
      id: {
       type: mongoose.Schema.Types.ObjectId,
       ref: "User"
      },
     username: String
    }
});

module.exports = mongoose.model("Manage", manageSchema);

轮次:


var express = require("express");
var router = express.Router();
var User        = require("../models/user");
var Manage = require ("../models/manages");

//Manage
    //Index Route for manage - view graphs + edit

router.get("/manage", isLoggedIn, function(req, res){
    Manage.find({}, function(err, manages){
        if(err){
            console.log("ERROR");
        } else {
            res.render("manage", {manages: manages});
        }
    });
});

    //NEW ROUTE - sends to forms page for Manage
router.get("/manage/new_admin0", isLoggedIn, function(req, res){
    res.render("manageForm");
});


    //CREATE ROUTE - POST request to manage
router.post("/manage", isLoggedIn, function (req, res){
    //create demog
    Manage.create(req.body.manage, function(err, newManage){
        if(err){
            console.log(err);
        } else {
            //add username and id to recruit
            newManage.user.id = req.user._id;
            newManage.user.username = req.user.username;
            //save recruit
            newManage.save();
             //redirect
             console.log(newManage);
            res.redirect("/manage");
        }
     });
 });

    //SHOW ROUTE - Specific info
router.get ("/manage/:id", checkOwnership, function(req, res){
    Manage.findById(req.params.id, function(err, foundManage){
        if(err){
            res.redirect("back");
        } else {
            res.render("showmanage", {manages: foundManage});
        }
    });
});

 // EDIT ROUTE - form to update existing data
router.get("/manage/:id/edit", checkOwnership, function(req, res){
        Manage.findById(req.params.id, function(err, foundManage){
                 res.render("editmanage", {manages: foundManage});               
        }); 
});

 //UPDATE ROUTE - use edit form info and update existing data
router.put("/manage/:id", checkOwnership, function(req, res){
    Manage.findByIdAndUpdate(req.params.id, req.body.manage, function(err, updateManage){
        if(err){
            res.redirect("back");
        } else {
          res.redirect("/manage/" + req.params.id);
        }
    });
});


 //middleware
function isLoggedIn(req, res, next){
    if(req.isAuthenticated()){
        return next();
    }
    res.redirect("/login");
}

function checkOwnership(req, res, next) {
    if(req.isAuthenticated()){
        Manage.findById(req.params.id, function(err, foundManage){
        if(err){
            res.redirect("back");
        } else {
            //check if user own data
            if(foundManage.user.id.equals(req.user._id)){
                 next();               
            } else {
                 res.redirect("back");
            }
          } 
        }); 
            } else {
                 res.redirect("back");
            }
}

module.exports = router;

请在不影响当前路线的情况下帮助您进行存储,最好是如何存储。

1 个答案:

答案 0 :(得分:0)

您可以使用$year$month$week之类的MongoDB聚合管道运算符根据日期对数据进行分组

{
    $project: {
        month: { $month: "$created" },
        year: { $year: "$created" },
    }
},
{
    $group: {
        _id: {
            year: '$year',
            month: '$month'
        },
        count: {
            $sum: 1
        }
    }
}

查看下面的参考链接,它将帮助您构建查询,