0

i want to update a date typed document to current date. My schema is

var appEventActivity = mongoose.Schema({
                    app_key : String,
                    e_id:String,//event id from appEvent
                    u_imei:String,//user imei from appUsers
                    startAt:{type: Date, default : Date.now()},
                    endAt:{type: Date, default : Date.now()}
                });

and my updated part of code is

AppEventActivity.findOneAndUpdate({_id:req.update_event_id},{$currentDate : {endAt:true}}, function(err,data){
            if(err)console.log(err);
            res.send(data);

        });

i have seen add created_at and updated_at fields to mongoose schemas and How do I update a property with the current date in a Mongoose schema on every save? but didn't get success.

Community
  • 1
  • 1
Ammar Hayder Khan
  • 1,287
  • 4
  • 22
  • 49

1 Answers1

0

The only problem I see here is the omission of { "new": true } in order to return the modified document:

AppEventActivity.findOneAndUpdate(
   { "_id": req.update_event_id },
   { "$currentDate" : { "endAt": true} },
   { "new": true },
   function(err,data){
      if(err)console.log(err);
      res.send(data);
  });

Without { "new": true } the document returned is the "un-modified" version "before" the update. Setting it shows the update you just performed.

This is a legacy pattern consistent with the MongoDB driver default behavior.

The $currentDate operator of MongoDB otherwise works as expected. Here is a complete listing:

var async = require('async'),
    mongoose = require('mongoose')
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/test');

var testSchema = new Schema({
  "name": String,
  "date": { type: Date, default: Date.now }
});

var Test = mongoose.model( 'Test', testSchema, 'test' );

async.series(
  [
    function(callback) {
      Test.remove({},callback);
    },
    function(callback) {
      Test.findOneAndUpdate(
        { "name": "me" },
        { "$currentDate": { "date": true } },
        { "new": true, "upsert": true  },
        function(err,doc) {
          console.log(doc);
          callback(err);
        }
      );
    }
  ],
  function(err) {
    if (err) throw err;
    mongoose.disconnect();
  }
);

With the output:

{ _id: 55e45ba528f7d03a06a2dd6e,
  name: 'me',
  __v: 0,
  date: Mon Aug 31 2015 23:50:29 GMT+1000 (AEST) }

So a new date was set on the server operation as opposed to on the client, which is what you are after.

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135