【问题标题】:nodeJS Dates & Mongoose saving to mongoDBnodeJS 日期和 Mongoose 保存到 mongoDB
【发布时间】:2016-10-14 11:55:19
【问题描述】:

我正在尝试创建一个架构,其中包含名为 startTime 和 endTime 的 Date 和 Number 类型的字段。我想要做的是让 startTime 是我现在正在工作的当前时间,然后 endTime 比开始时间晚 1 小时。这是我现在拥有的代码,但我无法找出解决方案。 endTime 未保存到数据库中。

var Mongoose = require('mongoose');
var Schema = Mongoose.Schema;
var testSchema = new Schema({
     startTime : {type: Date, default: Date.now, required: true},
     endTime : {type: Number, required: false},
});
testSchema.pre('save', function(next) {
     var testDocument = this;
     testDocument.endTime = Number(testDocument.startTime.valueOf() + 3600000);
     next();
}

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    使用下一个。设置 endTime 后调用 next();

    testSchema.pre('save', function(next) {
             var testDocument = this;
             testDocument.endTime = new Date();
             testDocument.endTime.setHours(testDocument.created_at.getHours() + 1)
             next();
        })
    

    【讨论】:

    • 嗨,对不起,我在实际代码中使用了 next()。刚刚忘记在这里上传了。
    • 你没有使用那个更新查询,对吧?使用与我在答案中发布的相同代码。它仅在您创建记录时起作用。
    • 在当前情况下,您无需在“保存”预挂钩中使用更新查询
    • 嗨,所以我尝试删除查询,但它没有保存任何内容,例如我正在尝试另一种解决方案,例如 TaskSchema.pre('save', function(next) { //更新任务的到期日期字段 var task = this; if (task.isNew) { console.log('here'); console.log(task.created_at.valueOf()); task.endTimeNumber = task.created_at.valueOf () + 3600000; } 下一个(); });但它不会将 endTimeNumber 保存到数据库中
    • 是否进入 if 条件。并且更好地使用您实际使用的确切代码更新问题。
    猜你喜欢
    • 2011-11-23
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2020-10-22
    • 2020-01-19
    • 2011-07-01
    • 2018-04-16
    • 1970-01-01
    相关资源
    最近更新 更多