Closed
Description
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the bug has not already been reported
Mongoose version
6.4.6
Node.js version
16.15.1
MongoDB server version
5.0.9
Description
Nested schema with a {timestamps: true}
inside a schema that is a Discriminator will fail to initialise timestamps with insertMany()
while successfully inserting the same object with create()
.
Removing {timestamps: true}
from the nested schema seems to fix the problem.
Steps to Reproduce
const { Schema, model, connect, connection } = require('mongoose')
const AssetSchema = new Schema(
{
url: {
type: String,
},
size: {
type: String,
},
},
{ timestamps: true }
)
const HeaderSectionSchema = new Schema({
title: {
type: String,
},
image: AssetSchema,
})
// Abstract section
const BaseSectionSchema = new Schema(
{
isVisible: { type: Boolean, default: true },
},
{ discriminatorKey: 'kind' }
)
// Main Schema
const PageSchema = new Schema(
{
sections: [BaseSectionSchema], // Same error without the array "sections: BaseSectionSchema"
},
{ collection: 'page', timestamps: true }
)
const HEADER_SECTION_KIND = 'header'
const sections = PageSchema.path('sections')
sections.discriminator(HEADER_SECTION_KIND, HeaderSectionSchema)
const Page = model('Page', PageSchema)
const seed = [
{
sections: {
isVisible: true,
kind: HEADER_SECTION_KIND,
title: 'h1',
},
},
{
sections: {
title: 'h2',
isVisible: true,
kind: HEADER_SECTION_KIND,
},
},
]
async function run() {
await connect(
'mongodb://localhost:27017/db'
)
// Inserts the document successfully
const p1 = await Page.create(seed[0])
console.log(p1)
// Fails instantiating the timestamps
// NOTE: Removing {timestamps:true} from Assets schema will fix this.
await Page.insertMany(seed)
await connection.dropDatabase()
await connection.close()
}
run()
Error Stack Trace
TypeError: Cannot read properties of undefined (reading 'now')
at EmbeddedDocument.schema.methods.initializeTimestamps (/Users/mb/app/sandbox/node_modules/mongoose/lib/helpers/timestamps/setupTimestamps.js:56:29)
at model.schema.methods.initializeTimestamps (/Users/mb/app/sandbox/node_modules/mongoose/lib/helpers/timestamps/setupTimestamps.js:72:18)
at /Users/mb/app/sandbox/node_modules/mongoose/lib/model.js:3363:20
at Array.map (<anonymous>)
at /Users/mb/app/sandbox/node_modules/mongoose/lib/model.js:3358:38
at /Users/mb/app/sandbox/node_modules/mongoose/lib/helpers/parallelLimit.js:49:16
at /Users/mb/app/sandbox/node_modules/mongoose/lib/model.js:3332:9
at /Users/mb/app/sandbox/node_modules/mongoose/lib/helpers/promiseOrCallback.js:25:16
at /Users/mb/app/sandbox/node_modules/mongoose/lib/document.js:2458:7
at complete (/Users/mb/app/sandbox/node_modules/mongoose/lib/document.js:2816:5)
Expected Behavior
No response