'Model.insertMany does not create createdAt or updatedAt timestamps

I have the following schema:

import mongoose, { Model, Schema, model, Types, Document } from "mongoose"
import { isEmpty } from "lodash"
import User from "./User"
import { generateImageStyles, ImageStylePrefixes } from "../server/common/util"
import { PresaveImageMetaData, PostsaveImageMetaData } from "./User"

export enum BadgeTrigger { ... }

export enum BadgeCategory { ... }

export interface IBadge {
  _id?: Types.ObjectId
  name: string,
  image: PresaveImageMetaData,
  triggerType?: BadgeTrigger,
  triggerAmount?: number,
  order?: number,
  hidden?: boolean,
  category: BadgeCategory,
  description?: string,
}

// Include fields that are generated automatically or virtuals that exist on the document by not the schema
// Instance methods also go here
export interface IBadgeDocument extends IBadge, Document<Types.ObjectId, unknown, IBadge> {
  image: PostsaveImageMetaData
}

// Static methods go here
interface IBadgeModel extends Model<IBadge> { }

const BadgeSchema = new Schema<IBadgeDocument, IBadgeModel>({
  name: { 
    type: String,
    required: true
  },
  image: { type: Object, required: true },
  triggerType: { 
    type: String,
    required: false,
    enum: Object.values(BadgeTrigger)
  },
  triggerAmount: { type: Number },
  order: { type: Number },
  // This acts as the "retired" field
  hidden: { type: Boolean },
  category: { 
    type: String,
    required: true,
    enum: Object.values(BadgeCategory),
  },
  description: { type: String }
},
{ timestamps: true }
)

// Add instance methods here
BadgeSchema.methods = {}

// Add model static methods
BadgeSchema.statics = { }

// Add presave / postsave and other middlework hooks here
BadgeSchema.pre('save', function (next) {
  const styles: ImageStylePrefixes[] =  ['large_square', 'medium_square', 'thumb_square']
  if (this.image && this.image.url && !this.image.styles) {
    this.image.styles = generateImageStyles(this.image.url, styles)
  }
  next()
})

async function deleteBadgeReferences(badge: 
  mongoose.Document<unknown, any, IBadge> 
  & IBadge 
  & { _id: any }
) {
  // Remove the badge references in the user model
  await User.updateMany({ _badges: badge._id }, {
    $pull: {
      _badges: badge._id
    }
  })
}

/**
 * Remove references to badge when it's deleted
 */
 BadgeSchema.pre('remove', async function(next) {
  await deleteBadgeReferences(this)
  next()
 })

 BadgeSchema.pre('deleteOne', async function(next) {
  await deleteBadgeReferences(this)
  next()
 })

const Badge = model<IBadgeDocument>('Badge', BadgeSchema)

export default Badge

I create an array of badges to add as an array like so:

  const playerRatingBadges: IBadge[] = [
    {
      _id: new Types.ObjectId("000000000000000000000004"),
      name: "Player Rating 1.0 Test Badge",
      image: TestImageData,
      category: BadgeCategory.Milestones,
      description: "Desc for player rating test badge",
      triggerAmount: 1.0,
      triggerType: BadgeTrigger.PlayerRating
    },
    {
      _id: new Types.ObjectId("000000000000000000000005"),
      name: "Player Rating 3.5 Test Badge",
      image: TestImageData,
      category: BadgeCategory.Milestones,
      description: "Desc for player rating test badge",
      triggerAmount: 3.5,
      triggerType: BadgeTrigger.PlayerRating
    },
    {
      _id: new Types.ObjectId("000000000000000000000006"),
      name: "Player Rating 6.0 Test Badge",
      image: TestImageData,
      category: BadgeCategory.Milestones,
      description: "Desc for player rating test badge",
      triggerAmount: 6.0,
      triggerType: BadgeTrigger.PlayerRating
    }
  ]

And then call the insertMany as so await Badge.insertMany(playerRatingBadges)

However, when viewing the data in the database I see the following result:

{ 
    "_id" : ObjectId("000000000000000000000004"), 
    "name" : "Player Rating 1.0 Test Badge", 
    "image" : {
        "url" : "version2/jahfkjnasdkjfbnajsdbfhjb.photo.jpg", 
        "type" : "jpg", 
        "name" : "photo.jpg", 
        "styles" : {
            "thumb_square" : "thumb_square/jahfkjnasdkjfbnajsdbfhjb.photo.png", 
            "large_square" : "large_square/jahfkjnasdkjfbnajsdbfhjb.photo.png"
        }
    }, 
    "triggerType" : "PlayerRating", 
    "triggerAmount" : NumberInt(1), 
    "category" : "milestones", 
    "description" : "Desc for player rating test badge", 
    "__v" : NumberInt(0)
}
{ 
    "_id" : ObjectId("000000000000000000000005"), 
    "name" : "Player Rating 3.5 Test Badge", 
    "image" : {
        "url" : "version2/jahfkjnasdkjfbnajsdbfhjb.photo.jpg", 
        "type" : "jpg", 
        "name" : "photo.jpg", 
        "styles" : {
            "thumb_square" : "thumb_square/jahfkjnasdkjfbnajsdbfhjb.photo.png", 
            "large_square" : "large_square/jahfkjnasdkjfbnajsdbfhjb.photo.png"
        }
    }, 
    "triggerType" : "PlayerRating", 
    "triggerAmount" : 3.5, 
    "category" : "milestones", 
    "description" : "Desc for player rating test badge", 
    "__v" : NumberInt(0)
}
{ 
    "_id" : ObjectId("000000000000000000000006"), 
    "name" : "Player Rating 6.0 Test Badge", 
    "image" : {
        "url" : "version2/jahfkjnasdkjfbnajsdbfhjb.photo.jpg", 
        "type" : "jpg", 
        "name" : "photo.jpg", 
        "styles" : {
            "thumb_square" : "thumb_square/jahfkjnasdkjfbnajsdbfhjb.photo.png", 
            "large_square" : "large_square/jahfkjnasdkjfbnajsdbfhjb.photo.png"
        }
    }, 
    "triggerType" : "PlayerRating", 
    "triggerAmount" : NumberInt(6), 
    "category" : "milestones", 
    "description" : "Desc for player rating test badge", 
    "__v" : NumberInt(0)
}
{ 
    "_id" : ObjectId("000000000000000000000003"), 
    "name" : "Milestone Test Badge", 
    "image" : {
        "url" : "version2/jahfkjnasdkjfbnajsdbfhjb.photo.jpg", 
        "type" : "jpg", 
        "name" : "photo.jpg", 
        "styles" : {
            "thumb_square" : "thumb_square/jahfkjnasdkjfbnajsdbfhjb.photo.png", 
            "large_square" : "large_square/jahfkjnasdkjfbnajsdbfhjb.photo.png"
        }
    }, 
    "category" : "milestones", 
    "description" : "Desc for milestone test badge", 
    "createdAt" : ISODate("2022-04-25T17:39:10.279+0000"), 
    "updatedAt" : ISODate("2022-04-25T17:39:10.279+0000"), 
    "__v" : NumberInt(0)
}

The badge that has the createdAt and updatedAt timestamps is the badge that was created in a different location using Badge.create({ ... }). Does auto management of timestamps just not work with insertMany?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source