Introduction to mongoose modified at time automatic recording plug-in

Posted by amazinggrace1983 on Mon, 28 Oct 2019 03:04:52 +0100

Mongoose modified at is a mongoose plug-in that automatically updates the field change time and records it to the database, similar to the timestamps function of mongoose.

Usage scenarios

Let's consider a scenario. We have an article release and display requirement. The data model is as follows.

const schema = new mongoose.Schema({
  // Article title
  title: String,
  // Draft or not
  is_draft: Boolean,
  // Recommendation
  is_recommended: Boolean,
  // More fields...
})

When we display the latest article list, it should be displayed in reverse order of the time when the article was first published. Because the article can be saved as a draft and edited many times, we can't use the createdAt or updatedAt provided by Mongoose as the first publishing time. The correct way is to make sure that the user publishes the article instead of saving it as a draft every time the article is created or updated. Then record this time, and use this time as the first release time.

To achieve this function, we need to deal with it in the code logic layer, which is feasible but a little coupling, or we need to encapsulate a Mongoose middleware to do this, but now you can leave it to a tested, API elegant plug-in ModifiedAt to deal with it.

Install the plug-in first.

npm install mongoose-modified-at --save

Then make a simple configuration during Schema initialization, as follows.

import modifiedAt from 'mongoose-modified-at'

// Before the mongoose.model call
schema.plugin(modifiedAt, {
  // Function name will be written to the database as field name
  publishedAt(doc) {
    // When the function return value is true, the time is recorded
    return !doc.is_draft
  },
  // So is the recommendation
  recommendedAt(doc) {
    return doc.is_recommended
  },
})

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

When the document is saved or updated with the is "draft field and the value is false, the plug-in will record the time and write it to the database together with the publishedAt field you declared.

An example is as follows:

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

The results are as follows (database):

{
  "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"),
  // More fields...
}

API introduction

The above is the rich API form of ModifiedAt, i.e. object format. All parameter options are as follows.

schema.plugin(modifiedAt, {
  // Set listening field
  fields: ['name', 'status', 'another'],
  // Set suffix
  suffix: '_your_suffix',
  // Set path default behavior
  select: true,
  // Custom fields
  customField(doc) {
    // Do something you want to do, and then return the Boolean value to tell the plug-in whether to record the time
  },
})

🍎 parameter interpretation:

  • fields: set the listening field. When creating or updating a document, if there is a listening field, it will automatically take the form of field name + suffix as the field, and record the update time to the field. Optional, Array type.
  • Suffix: set the suffix. The default value is "modifiedAt". Optional, String type.
  • select: set the default path behavior, which is true by default. Refer to Mongoose documentation . Optional, Boolean type.
  • customField: a custom field. This field will not be suffixed. It is added to the parameter in the form of a function for custom functions. The function receives unique document parameters. When the return value of the function is true, the time will be recorded to this field.

Simplified API

🚀 in order to increase the simplicity and ease of use of the API and avoid overloading, ModifiedAt only adds a simplified parameter format, as follows.

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

This means that the fields option is extracted as a parameter, and the result written to the database is as follows.

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

Asynchronous Support

You need Node.js to support async/await.

import P from 'bluebird'

const petSchema = new mongoose.Schema({
  name: String,
  age: Number,
  sex: String,
  // 1: in purchase, 2: purchased, 3: sold
  status: Number,
})

petSchema.plugin(modifiedAt, {
  // Record when you bought
  async boughtAt(doc) {
    // Delay 1s
    await P.delay(1000)
    return doc.status === 2
  },
  // Record when it was sold
  soldAt(doc) {
    return doc.status === 3
  },
})

Support Mongoose 4.x

If you are using Mongoose 4.x now, you need to use plug-in 1.x. Documents can be viewed here.

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

"100%" test coverage

29 test cases, 777 lines of code, "100%" test coverage.

details

For more details, please move to GitHub document. Here.

Last

1,Support me, please point to Star, contribution point to Fork 😘

2. Published in Bump lab blog Or wechat public account, welcome to follow us, MMD!

Topics: node.js Mongoose Database npm github