日期输入无法正确进入nodejs中的数据库

时间:2018-06-16 07:05:15

标签: node.js mongodb

我有这样的问题。我正在使用express4制作一个Web API。在他们中,我创建了一个保存数据的功能。我在这里提供我的控制器。

const express = require('express');
var router = express.Router();

var  Reservation  = require('../models/reservation');

router.post("/create",function (req,res) {
    const newReservation = new Reservation({
        date: req.body.date,
        from: req.body.from,
        to: req.body.to,
        lab: req.body.lab,
        name: req.body.name,
        email: req.body.email,
        role: req.body.role,
        year: req.body.year,
        reason: req.body.reason,
        state: "Not Comfirm"
    });

    Reservation.saveReservation(newReservation, function (err, reservation) {
        if (reservation) {
            res.send(reservation);
        }

        else {
            console.log('Error in User save :' + JSON.stringify(err, undefined, 2));
        }
    });

});

router.get('/notComfirmed', function (req, res) {
    Reservation.findNotComfirmed(function (err, reservations) {
        if(err) throw err;

        if (!reservations){
            res.json({state:false,msg:"No reservations found"});
        }

        if(reservations){
            res.json(reservations);
        }

    })
});


module.exports = router;

这里提供我的模特。

const mongoose = require('mongoose');
const schema = mongoose.Schema;

const reservationSchema = new schema({
    date:{type:Date, required:true},
    from:{type:String},
    to:{type:String, required:true},
    lab:{type:String, required:true},
    name:{type:String, required:true},
    email:{type:String, required:true},
    role:{type:String, required:true},
    year:{type:String},
    reason:{type:String, required:true},
    state:{type:String, required:true},
});

const Reservation = module.exports= mongoose.model("Reservation",reservationSchema );

module.exports.saveReservation = function (newReservation, callback) {
    newReservation.save(callback);
}


module.exports.findBYDateAndTime = function(date, time, lab, callback){
    const query = {date:date,time:time, lab:lab};
    Reservation.findOne(query,callback);
}

module.exports.findNotComfirmed= function (callback) {
    const query = {state: "Not Comfirm"};
    Reservation.find(query, callback);
}

当我和邮递员一起尝试时。使用时区保存日期。例如,如果我发送日期为" 2018-06-19"它被保存在数据库中作为" 2018-06-19 05:30:00.000"。我想删除该时区。我在google和StackOverflow中搜索了很多时间。那里的例子不足以满足我的要求。那么有人可以帮我解决这个问题吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

也许这会对你有所帮助link。这是与Mongoose一起使用的DateOnly库的实现。

它只是一个猫鼬日期模块,存储日期而不用担心时区请告诉我你是否解决了问题