Auto‑Track Publish Times in Mongoose with the modified‑at Plugin

This guide explains how the mongoose-modified-at plugin automatically records publication timestamps for MongoDB documents, covering installation, schema configuration, API options, simplified usage, async support, compatibility with Mongoose 4.x, and test‑coverage details.

Aotu Lab
Aotu Lab
Aotu Lab
Auto‑Track Publish Times in Mongoose with the modified‑at Plugin

Overview

The mongoose-modified-at plugin automatically updates timestamp fields in MongoDB documents whenever specified conditions are met, providing functionality similar to Mongoose's built‑in timestamps but with customizable logic for publishing and recommendation events.

Installation

npm install mongoose-modified-at --save

Basic Usage

After installing, import the plugin and attach it to a schema before creating the model. The plugin can record a publishedAt field when a document is saved with is_draft set to false, and a recommendedAt field when is_recommended is true.

import modifiedAt from 'mongoose-modified-at';

schema.plugin(modifiedAt, {
  publishedAt(doc) {
    return !doc.is_draft;
  },
  recommendedAt(doc) {
    return doc.is_recommended;
  }
});

const Article = mongoose.model('Article', schema);

Creating a document:

await Article.create({
  title: 'Document Title',
  is_draft: false,
  is_recommended: true
});

Resulting document in the database includes automatically added timestamps:

{
  "title": "Document Title",
  "is_draft": false,
  "is_recommended": true,
  "publishedAt": ISODate("2019-09-27T03:11:07.880Z"),
  "recommendedAt": ISODate("2019-09-27T03:11:07.880Z")
}

API Options

The plugin accepts an options object with several configurable properties:

schema.plugin(modifiedAt, {
  fields: ['name', 'status', 'another'],
  suffix: '_your_suffix',
  select: true,
  customField(doc) {
    // return true to record the time for a custom field
  }
});
fields

: Array of field names to watch; when any of these fields change, a timestamp field named fieldName + suffix is created. suffix: String appended to watched field names (default _modifiedAt). select: Boolean indicating whether the generated timestamp fields are selected by default (default true). customField: Function returning a Boolean to decide whether to record a timestamp for a custom field without a suffix.

Simplified API

For a more concise syntax, the plugin can be invoked with an array of field names:

schema.plugin(modifiedAt, ['name', 'status']);

This automatically creates name_modifiedAt and status_modifiedAt fields on document updates.

{
  "name": "Tom",
  "status": 1,
  "name_modifiedAt": ISODate("2019-09-27T03:13:17.888Z"),
  "status_modifiedAt": ISODate("2019-09-27T03:13:17.888Z")
}

Async Support

The plugin works with Node.js versions that support async/await. Asynchronous custom functions can perform asynchronous checks before deciding to record a timestamp.

import P from 'bluebird';

petSchema.plugin(modifiedAt, {
  async boughtAt(doc) {
    await P.delay(1000); // simulate async operation
    return doc.status === 2;
  },
  soldAt(doc) {
    return doc.status === 3;
  }
});

Mongoose 4.x Compatibility

If you are using Mongoose 4.x, install the 1.x version of the plugin:

npm install mongoose-modified-at@1 --save

Test Coverage

The plugin is covered by 29 test cases spanning 777 lines of code, achieving 100% test coverage.

Test coverage chart
Test coverage chart

Further Details

Additional configuration details and advanced usage examples are available in the plugin's GitHub repository documentation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaScriptpluginNode.jsMongoDBMongoose
Aotu Lab
Written by

Aotu Lab

Aotu Lab, founded in October 2015, is a front-end engineering team serving multi-platform products. The articles in this public account are intended to share and discuss technology, reflecting only the personal views of Aotu Lab members and not the official stance of JD.com Technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.