Cannot set default value of path `stats` to a mongoose Schema instance

Viewed 828

Probably this issue arose due to mongoose compatibility. I am working on an existing app. Today, all of sudden this issue started to appear when I tried to restart the app but it failed for the following error

Cannot set default value of path stats to a mongoose Schema instance

The stack trace took me to line number 47 of my User model. The line said.

stats: { type: UserStatsSchema, default: UserStatsSchema },

Right above the new Schema() call in user.js modal file, UserStatsSchema is defined

const UserStatsSchema = new Schema({
    numLikes: { type: Number, default: 0 },
    numPosts: { type: Number, default: 0 }
}, {_id: false});

I tried to figure out by searching over the internet. Since I am new to mongoose and it's Schema typecasting I am not sure what do I need to fix this issue.

2 Answers

You should make your nested schema default to returning a function that returns an empty object. Mongoose will handle type-casting that to your UserStatsSchema type and ensure the defaults you configured.

stats: { type: UserStatsSchema, default: () => ({}) },

This is based on these 2 issues from Mongoose's official Github

  1. https://github.com/Automattic/mongoose/issues/9104
  2. https://github.com/Automattic/mongoose/issues/8751

We made a small improvement in 8fea1d9 that removes most of the performance impact, but the above script still ends up being 2x slower than if you don't have the default. So in 32c5ed0 we made Mongoose throw an error if you set a path's default to a Mongoose schema instance. There's no reason to ever do that anyway.

Later describes why it was not pushed as a Major Version update

I admit this change is a bit heavy for a patch, but seeing as how (1) setting a default to a schema instance doesn't do anything useful, and (2) it has a significant performance impact, I figured it was worth it to get this change out sooner rather than later. Sorry for any trouble.

Replaced:

stats: { type: UserStatsSchema, default: UserStatsSchema }

with

stats: [ UserStatsSchema ]
Related