Giter Site home page Giter Site logo

mongoose-timestamp's Introduction

Mongoose Timestamps Plugin

Build Status Dependency Status devDependency Status Downloads Monthly Downloads Total

Simple plugin for Mongoose which adds createdAt and updatedAt date attributes that get auto-assigned to the most recent create/update timestamp.

Installation

npm install mongoose-timestamp

Usage

var timestamps = require('mongoose-timestamp');
var UserSchema = new Schema({
    username: String
});
UserSchema.plugin(timestamps);
mongoose.model('User', UserSchema);
var User = mongoose.model('User', UserSchema)

The User model will now have createdAt and updatedAt properties, which get automatically generated and updated when you save your document.

var user = new User({username: 'Prince'});
user.save(function (err) {
  console.log(user.createdAt); // Should be approximately now
  console.log(user.createdAt === user.updatedAt); // true
  // Wait 1 second and then update the user
  setTimeout( function () {
    user.username = 'Symbol';
    user.save( function (err) {
      console.log(user.updatedAt); // Should be approximately createdAt + 1 second
      console.log(user.createdAt < user.updatedAt); // true
    });
  }, 1000);
});

findOneAndModify (mongoose >= 4.0.1)

Mongoose 4.0.1 added support for findOneAndModify hooks. You must the mongoose promise exec for the hooks to work as mongoose uses mquery when a callback is passed and the hook system is bypassed.

User.findOneAndUpdate({username: 'Prince'}, { password: 'goatcheese' }, { new: true, upsert: true })
            .exec(function (err, updated) {
                console.log(user.updatedAt); // Should be approximately createdAt + 1 second
                console.log(user.createdAt < user.updatedAt); // true
            });

You can specify custom property names by passing them in as options like this:

mongoose.plugin(timestamps,  {
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

Any model's updatedAt attribute can be updated to the current time using touch().

License

(The MIT License)

Copyright (c) 2012-2016 Nicholas Penree <[email protected]>

Based on mongoose-types: Copyright (c) 2012 Brian Noguchi

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

mongoose-timestamp's People

Contributors

almostagile avatar bnoguchi avatar chapel avatar drudge avatar inxilpro avatar lchenay avatar lethalbrains avatar linusbrolin avatar qwasibuild avatar turbo87 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongoose-timestamp's Issues

wish: allow customizing the name of the columns

Thanks for this plugin.

It would be nice if the column names 'updatedAt' and 'createdAt' could be customized.

In our case, we are considering adding it to an existing system where we already have a different naming convention established.

Timestamp Auto closed the TCP cause MongoNetworkError

I Worked with

  • "mongoose": 5.6.9
  • "mongoose-timestamp": 0.6.0

Do you want to request a feature or report a bug?
I want to report a bug.

What is the current behavior?
When I working with a long process task like transfer data from MySQL to Mongo Atlas.
I try so many time but finally I got this:

(node:74121) UnhandledPromiseRejectionWarning: MongoNetworkError: connection 2 to cluster0-shard-00-01-ug0nb.gcp.mongodb.net:27017 closed
    at TLSSocket.<anonymous> (/Users/kayac/Projects/Work/Backend_Server/node_modules/mongodb-core/lib/connection/connection.js:352:9)
    at Object.onceWrapper (events.js:288:20)
    at TLSSocket.emit (events.js:200:13)
    at net.js:586:12
    at TCP.done (_tls_wrap.js:479:7)

And My config like this:

    const db = await mongoose.connect(path, {
        useNewUrlParser: true,
        socketTimeoutMS: 600 * 1000,
        connectTimeoutMS: 600 * 1000,
        autoReconnect: true,
        keepAlive: true,
        reconnectTries: 30,
        poolSize: 20,
    });

socketTimeoutMSand connectTimeoutMS both doesn't help.

But I remove the

const timestamps = require('mongoose-timestamp');
Schema.plugin(timestamps);

And My task success.

Did mongoose timestamp auto close the TCP connection when process too long?

Global configuration/setup instead of by each model

First: Thanks!

Second: I tried to research about the ability to enabled timestamps 'globally'.
Is there a way to enable timestamps to the mongoose object?

like with promises:

let mongoose = require('mongoose');

mongoose.Promise = global.Promise;

various timezone

If i want to search in createdAt for specific timezone like Turkey timezone I have to convert it to uct?

TypeError: documentSchema.plugin is not a function

did an npm install mongoose-timestamp, implemented the plugin, as follows:

var timestamps = require('mongoose-timestamp');
var mongoose = require("mongoose");

var mongoSchema = mongoose.Schema;

var documentSchema = {
    name: String,
 isPayed: { type: Boolean, default: false }
};

documentSchema.plugin(timestamps);
module.exports = mongoose.model('documents', documentSchema);

When starting node, the compiler returns folliowing error:

PS C:\Users\paul\Programming\cli\ngEstrich_Server> node server
C:\Users\paul\Programming\cli\ngEstrich_Server\models\documents.js:65
documentSchema.plugin(timestamps);
               ^

Retrive documents based on sort order for array of subdocuments

I have documents like below(i am using node.js and mongoose).

{                                                             
        "id" : 1,                                             
        "name" : "strs",                                      
        "subs" : [                                            
                {                                             
                        "sortorder" : 5,                          
                        "type" : "volvo"                          
                },                                            
                {                                             
                        "sortorder" : 2,                          
                        "type" : "benz"                          
                }                              
        ]                                                     
}                                                             
{                                                             
        "id" : 2,                                             
        "name" : "newname",                                   
        "subs" : [                                            
                {                                             
                        "sortorder" : 3,                          
                        "type" : "volvo"                           
                },                                            
                {                                             
                        "sortorder" : 1,                          
                        "type" : "benz"                           
                }                                    
        ]                                                     
}     

When i query for subs.type: volvo , i need to sort the documents based on the sortorder for volvo. I want output like below.

{                                                             
        "id" : 2,                                             
        "name" : "newname",                                   
        "subs" : [                                            
                {                                             
                        "sortorder" : 3,                          
                        "type" : "volvo"                           
                },                                            
                {                                             
                        "sortorder" : 1,                          
                        "type" : "benz"                           
                }                                    
        ]                                                     
}     
{                                                             
        "id" : 1,                                             
        "name" : "strs",                                      
        "subs" : [                                            
                {                                             
                        "sortorder" : 5,                          
                        "type" : "volvo"                          
                },                                            
                {                                             
                        "sortorder" : 2,                          
                        "type" : "benz"                          
                }                              
        ]                                                     
}                                                             

Won't work with `insertMany` method

It seems like this plugin does not support insertMany method because it won't call save hook.

And I find this issue #723 may be helpful...

Can you support this feature ๏ผŸ

Thanks.

mongoose-timestamp adds 4 properties to collection when I customize the names

Hello,
I have the following in my code:

var mongoose = require('mongoose'),
      Schema = mongoose.Schema,
      timestamps = require('mongoose-timestamp');
var ItemSchema = new Schema({
      name: String
});
mongoose.plugin(timestamps,  {
    createdAt: 'added_at',
    updatedAt: 'last_updated'
});
ItemSchema.plugin(timestamps);

however when I look at my item collection using mongo command line I see that there is 4 properties (added_at, last_updated, createdAt and updatedAt)
what have I done wrong?
( @drudge ? )

Object function Date() has no method 'get'

When setting the names of the createdAt and updatedAt properties, I am getting the following error:

node_modules/mongoose-timestamp/index.js:34
.get( function () {
^
TypeError: Object function Date() { [native code] } has no method 'get'
at timestampsPlugin (node_modules/mongoose-timestamp/index.js:34:8)
at Schema.plugin (node_modules/mongoose/lib/schema.js:570:3)
at Mongoose._applyPlugins (node_modules/mongoose/lib/index.js:403:12)
at Mongoose.model (node_modules/mongoose/lib/index.js:320:12)
at NativeConnection.Connection.model (node_modules/mongoose/lib/connection.js:600:23)

This also appears to be the error that is causing the Travis tests to fail on the continuing integration server.

Bug

I believe that line 31 should be using createdAt the variable, not "createdAt" the string

 if (schema.path('createdAt')) {

can you override the dates? (to manually set them)

I have a situation where I am migrating some data and would like to preserve the modified dates from the original record. Can I manually set the created/modified dates and then have mongoose-timestamp skip its action so they are preserved?

Object function Date() has no method 'get'

When setting the names of the createdAt and updatedAt properties, I am getting the following error:

 node_modules/mongoose-timestamp/index.js:34
        .get( function () {
         ^
  TypeError: Object function Date() { [native code] } has no method 'get'
      at timestampsPlugin (node_modules/mongoose-timestamp/index.js:34:8)
      at Schema.plugin (node_modules/mongoose/lib/schema.js:570:3)
      at Mongoose._applyPlugins (node_modules/mongoose/lib/index.js:403:12)
      at Mongoose.model (node_modules/mongoose/lib/index.js:320:12)
      at NativeConnection.Connection.model (node_modules/mongoose/lib/connection.js:600:23)

This also appears to be the error that is causing the Travis tests to fail on the continuing integration server.

Doesn't support nested keys

Correct me if I'm wrong, but this doesn't work:

Schema.plugin(require('mongoose-timestamp'), {
  createdAt: 'created.at',
  updatedAt: 'updated.at'
});

When used with passport-local-mongoose and mongoDB 3.0 we get this issue

[TypeError: Cannot assign to read only property 'checkKeys' of true]

passport-local-mongoose 1.0.1
timestamps 0.4.0

var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var timestamps = require('mongoose-timestamp');

var Schema = mongoose.Schema;

exports.User = mongoose.model('User', new Schema({
  username: {
    type: String,
    index: {
      unique: true,
      sparse: true
    }
  },
  email: String
}, {
  safe: true,
  strict: true
}).plugin(passportLocalMongoose, {}).plugin(timestamps));

removing the timestamps plugin gets this working, but I liked the timestamps plugin.

Virtual `createdAt` not available on document.toJSON

In earlier version 0.1.1 i was not specifying any createdAt in my schema file.
mongoose-timestamp used to add and and setupvirtuals

Now mongoose-timestamp is adding virtuals only if i have explicitly defined the createdAt field.

Time to deprecate this package?

Hi,

It seems that mongoose has been supporting timestamps option for quite a while now. Is there any need to use mongoose-timestamp anymore or there is some sense to point people to mongoose docs and deprecate the module?

Thanks for all great work on this module, I've been using it for years and currently upgrading some of the old projects to use the latest mongoose, so that's how I stumbled upon this issue :)

http://mongoosejs.com/docs/guide.html#timestamps

Cheers,
Andrej

If createdAt or updatedAt is already present, ignore adding it

If a schema already has createdAt field, dont add it. Instead, add updatedAt field alone and maintain it. Vice versa for the updatedAt field.

Right now in version 0.3.0, this is the error I get when createdAt is already there and if I use mongoose-timestamp in that schema.

/Users/Anand/xyz/node_modules/mongoose-timestamp/index.js:34
      .get( function () {
       ^
TypeError: Object #<Object> has no method 'get'
    at timestampsPlugin (/Users/Anand/xyz/node_modules/mongoose-timestamp/index.js:34:8)
    at Schema.plugin (/Users/Anand/xyz/node_modules/mongoose/lib/schema.js:570:3)
    at Object.<anonymous> (/Users/Anand/xyz/models/session_token.js:12:20)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/Users/Anand/xyz/models/agent.js:17:20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.