Mongo Db 时间格式

3

我想在MongoDB中保存时间,以便为学校添加教师的可用性。如何将一天的时间存储在MongoDB中,作为一个字符串呢?(我想存储如下格式:03:30 PM)请帮我找到解决方案。


1
为什么不直接将时间存储为从当天开始的毫秒数呢?这比字符串占用更少的空间,并且具有更广泛的通用性。 - Neil Lunn
1个回答

3

您可以使用Mongoose用户模式的pre函数,每次使用该模式添加任何内容时都会触发。在其中使用条件函数来确定如何保存特定的模式模型。我已经完成了您的时间模型。如果有任何疑问,请告诉我。

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var UserSchema = new Schema({
time: String
});


UserSchema.pre('save',
function (next) {
    if (!this.time) {
        var newdate = new Date();
        var Fulllocaltime =  newdate.toLocaleString('en-US');
        var array = Fulllocaltime.split(" ");
        var finaloutput = array[1]+' '+array[2];

        this.time =finaloutput;
    }
    next();
}
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接