JohnyBro
JohnyBro

Reputation: 361

Wrong Date in mongoose

I don't know why but when I create a new document in mongoose the date isn't the actual date.

This is my schema :

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();
});

Why the "created_at" field is not the date of creation of my document ?

Upvotes: 0

Views: 1564

Answers (2)

mayank
mayank

Reputation: 460

you need to define your schema as below

 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]
 });

in case you want to use the plugin to add created time you can use it as follow

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

//use npm install to install them

Upvotes: 1

André Kreienbring
André Kreienbring

Reputation: 2509

You could just define:

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

Every time a document is created this will set the created_at property to the current date.

Upvotes: 0

Related Questions