首页 文章

猫鼬的错误日期

提问于
浏览
0

我不知道为什么,但是当我在mongoose中创建一个新文档时,日期不是实际日期 .

这是我的架构:

var WhispSchema = new mongoose.Schema({
    text : String,
    created_at : {type : Date, index : true},
    pos : {latitude: Number, longitude: Number},
    created_by : {type : Schema.Types.ObjectId, ref : "UserSchema"},
    upvote : {type : Number, default : 0},
    downvote : {type : Number, default : 0},
    comment : [CommentSchema]
});

WhispSchema.pre("save", function (next){
    var currentDate = new Date();

    if(!this.created_at)
    {
        this.created_at = currentDate;
    }
    next();
});

为什么“created_at”字段不是我的文档创建日期?

2 回答

  • 1

    您需要定义您的架构,如下所示

    var WhispSchema = new mongoose.Schema({
    text : String,
    created_at : {type : Date, index : true,default:Date.now()},
    pos : {latitude: Number, longitude: Number},
    created_by : {type : Schema.Types.ObjectId, ref : "UserSchema"},
    upvote : {type : Number, default : 0},
    downvote : {type : Number, default : 0},
    comment : [CommentSchema]
     });
    

    如果你想使用插件添加创建的时间,你可以使用它如下

    var WhispSchema = require('mongoose-timestamp');
     WhispSchema.plugin(timestamps);
    

    //使用npm install来安装它们

  • 0

    你可以定义:

    created_at : {type: Date, index : true, default: Date.now}
    

    每次创建文档时,这都会将created_at属性设置为当前日期 .

相关问题