Reputation: 17581
I want to add the creation date to results returned by mongoose. I know the _id property of a mongodb record has the creation date embedded in it, but I'm not sure how to add it to the result set so that I can use it in my client side application.
Any ideas on how to add that property dynamically to the results set?
Upvotes: 2
Views: 1180
Reputation: 7919
Mongoose can do it for you automatically. according to timestamp option in Mongoose just do something like this :
var nSchema=new Schema({
name:String,
...
timestamps: { createdAt: 'created_at' },
...
});
also you can track for update with updateAt
Upvotes: 1
Reputation: 2295
I prefer the second way of ma08.Add a created field and use the default value to Date.now.This method automatically creates the current date as the created date.
var nSchema=new Schema({
name:String,
...
created: {type:Date, default:Date.now},
...
});
Upvotes: 0
Reputation: 3734
If you are willing to use _id
's timestamp as the date created
var fooSchema = new Schema({
name: String,
...
},
{
toObject: { virtuals: true },
toJSON: { virtuals: true }
}
)
fooSchema.virtual('created')
.get(function(){
return this._id.getTimestamp();
});
You can access the field created
to get the timestamp.
The toObject
(doc) and toJson
(doc) options are used to keep our virtual field(created) when converting from a mongoose document. Using toJson
might suffice I guess, depends on your usage.
If you are not willing to use _id
's timestamp(there are many arguments that it is not advisable when operating across multiple instances), you can put it in a separate field like
var fooSchema = new Schema({
name: String,
created: {type: Date, default: Date.now},
});
This will set created
to the timestamp the object is first saved.
Upvotes: 2