0

I have a basic web app that I can add a user, update a user, find a user and delete a user. I'm doing this on Postman using Post, Get, and Delete.

I'm trying to add a field to my MongoDB (through Mongoose) that will automatically insert the current date when I create a new user. I've tried a few different methods from questions I've found on this site, but none seem to be working. This is the schema for the db. Thanks

var mongoose = require('mongoose');

var userSchema = mongoose.Schema({

name: String,
times:{
        description:String
      }

});

module.exports = mongoose.model('User', userSchema);
Theresa
  • 3,515
  • 10
  • 42
  • 47
James
  • 47
  • 2
  • 8
  • Possible duplicate of [add created\_at and updated\_at fields to mongoose schemas](http://stackoverflow.com/questions/12669615/add-created-at-and-updated-at-fields-to-mongoose-schemas) – Patrick Motard May 21 '16 at 00:19
  • Just set the default value for the field to `Date.now()` in your schema. for updatedAt, you would need to set manually – aarosil May 21 '16 at 01:27

1 Answers1

0

Schemas have a few configurable options which can be passed to the constructor or set directly. If set timestamps, mongoose assigns createdAt and updatedAt fields to your schema, the type assigned is Date. By default, the name of two fields are createdAt and updatedAt, custom the field name by setting timestamps.createdAt and timestamps.updatedAt.

var mongoose = require('mongoose');

var userSchema = mongoose.Schema({
  name: String,
  times: {
    description: String
  }
}, {timestamps: {createdAt: 'created_at'}});

module.exports = mongoose.model('User', userSchema);
KibGzr
  • 2,053
  • 14
  • 15